gpt4 book ai didi

php - 从非限定类名中获取完全限定类名

转载 作者:行者123 更新时间:2023-12-04 17:01:10 28 4
gpt4 key购买 nike

我怎样才能使这项工作?

<?php
namespace Target {

class FooBar {

}
}

namespace Test {

use Target\FooBar;

$class = 'FooBar';

var_dump(new \ReflectionClass(new $class));

}
目前它失败了,因为反射类只能找到具有完整命名空间的类。如何更改它以便它从 use 语句中提取类?如果有我缺少的功能。尝试诸如 $class::class 之类的东西也只是犯了一个错误。
我的全部目的是能够像这样处理数组的注释:
<?php
namespace Target {
use Foo\Bar;

class FooBar {
/**
* @var Bar[]|null
*/
public ?array $foo;
}
}
也许我正在做的事情是不可能的,我应该在注释中使用完全限定的类名。
我正在使用 PHP7.4

最佳答案

恐怕这是不可能的。根据 PHP documentation在动态类名中应该使用完全限定的类名。

One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary.

<?php

namespace Target {
class FooBar
{
}
}

namespace Test {
$class = 'Target\FooBar';

var_dump(new \ReflectionClass(new $class));
}
作为替代方案,有一个选项可以解析 use 语句并从那里获取完全限定的类名,但这种方式有点麻烦。
github.com/Kdyby/ParseUseStatements

关于php - 从非限定类名中获取完全限定类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65291156/

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