Hack Language introduces the concept of generics to PHP. It allows a class or function or interface to define the type of it’s at the time of creation of its objects.
The rules that should be taken into consideration while writing generic methods are:
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.