3

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?

Josh Watzman
  • 7,060
  • 1
  • 18
  • 26
Thomas
  • 962
  • 1
  • 6
  • 12

1 Answers1

4

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!

Josh Watzman
  • 7,060
  • 1
  • 18
  • 26
  • Thanks for the answer. I have a follow up. It seems like hack generics don't work as I expect in general. Please see this gist: https://gist.github.com/leftyhitchens/03bf07f5566125c9ce39 Am I missing something? Or is this a known bug? – Thomas Oct 16 '14 at 15:51
  • That's actually going to be a syntax error -- make sure you are running the typechecker which enforces a lot of the language. (Recent versions of HHVM will also tell if you aren't doing this.) Info: http://docs.hhvm.com/manual/en/install.hack.bootstrapping.php – Josh Watzman Oct 16 '14 at 16:28