使用反射在Hack中获取PHP的通用类型

3

我正在使用HHVM进行Hack语言的探索,并且使用泛型。 我有以下基本仓库:

class BaseRepository<T>{
     public function __construct(T $model){
        ...
     }
}

然后我有一个名为UserRepository的子类,如下所示:
class UserRepository extends BaseRepository<User> {

}

我希望能够使用反射来在运行时获取T的类型。
我已经尝试了以下方法:
$reflectionClass = new ReflectionClass('UserRepository');
$parameters = $reflectionClass->getConstructor()->getParameters();
var_dump($parameters);

这将输出以下内容:

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"
  }

然后我遍历参数并调用: $parameter->getClass()

它返回null。

是否可能使用反射在运行时获取T的类型? 如果是,我该如何做到这一点?

1个回答

4

很遗憾,目前无法在运行时获取基因的实际类型。HHVM对其具有类型擦除语义,这意味着当我们运行代码时实际上不知道T的具体类型是什么。然而,能够做到这一点通常会很有用,我们已经考虑了如何添加这个功能,称为“具体化基因”。但这是一个非常复杂、涉及广泛的变化,因此您不应该期望它很快就会出现。抱歉!


谢谢您的回答。我有一个后续问题。通常情况下,似乎黑客泛型并不像我期望的那样工作。请参见此代码片段:https://gist.github.com/leftyhitchens/03bf07f5566125c9ce39 我是不是漏掉了什么?还是这是一个已知的错误? - Thomas
这实际上将是一个语法错误 - 确保您正在运行强制执行许多语言的类型检查器。(HHVM的最新版本也会告诉您是否没有这样做。)信息:http://docs.hhvm.com/manual/en/install.hack.bootstrapping.php - Josh Watzman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接