gpt4 book ai didi

Php Hack中使用反射获取泛型类型

转载 作者:搜寻专家 更新时间:2023-10-31 20:39:31 25 4
gpt4 key购买 nike

我正在使用 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"
}

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

返回 null。

是否可以使用反射在运行时获取 T 的类型?如果是这样,我该怎么做?

最佳答案

不幸的是,现在不可能在运行时获得实际的遗传学类型。 HHVM 对它们具有类型删除语义,这意味着我们在运行代码时实际上并不知道 T 的具体类型是什么。然而,能够做到这一点通常很有用,我们已经考虑了如何添加它,称为“具体化泛型”。但这是一个非常复杂、涉及的变化,所以你不应该期望很快就会发生。对不起!

关于Php Hack中使用反射获取泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26406123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com