I am exploring Hack with HHVM, and I am using generics. I have the following Base Repository:
class BaseRepository<T>{
public function __construct(T $model){
...
}
}
Then I have sub-class UserRepository like so:
class UserRepository extends BaseRepository<User> {
}
What I want to be able to do is use reflection to get the type of T at run time.
I have tried the following:
$reflectionClass = new ReflectionClass('UserRepository');
$parameters = $reflectionClass->getConstructor()->getParameters();
var_dump($parameters);
Which outputs the following:
array(1) {
[0]=>
object(ReflectionParameter)#854 (2) {
["info"]=>
array(9) {
["index"]=>
int(0)
["name"]=>
string(5) "model"
["type"]=>
string(0) ""
["type_hint"]=>
string(1) "T"
["function"]=>
string(11) "__construct"
["class"]=>
string(36) "BaseRepository"
["nullable"]=>
bool(true)
["attributes"]=>
array(0) {
}
["is_optional"]=>
bool(false)
}
["name"]=>
string(5) "model"
}
}
Then I iterate over the parameters and call: $parameter->getClass()
Which returns null.
Is it possible to get the type of T at run time using reflection? If so how would I do that?
Unfortunately it is impossible to get the actual type of genetics at runtime right now. HHVM has type erasure semantics for them, meaning we actually don't know what the specific type of T is when we're running the code. It would often be useful to be able to do this, however, and we've considered how to add this, called "reified generics". But its a very complex, involved change and so you shouldn't expect it any time soon. Sorry!