The rules that should be taken into consideration while writing generic methods are:
- The generic parameters must start with a Capital letter T.
- The generic method name should not be similar to any non-generic method name.
- Nullable T is supported ( i.e. ?T).
- Hack does not casting to T type or creating object of typeT.
<?hh class GenericClassCraeting generic class objects:{ private T $val; public function __construct(T $x) { $this->val = $x; } public function getValue(): T { return $this->val; } }
<?hh function main_func() { $objInt = new GenericClass(3); $objStr = new GenericClass ("Hi"); $objArray = new GenericClass(array()); echo $objInt->getValue()."\n"; echo $objStr->getValue()."\n"; echo $objArray->getValue()."\n"; } main_func();Generic Class:
<?hh // generic interface interface GenericInterface{ public function addValue(T$item): void; public function removeValue(): T; } class UseClassimplements Box //Do some code }{
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.
Click to see the code!
To insert emoticon you must added at least one space before the code.