从 PHP 7.1 开始,他们引入了 const 可见性,我需要通过反射来阅读它。我像这样创建了我的 ReflectionClass
:
$rc = new ReflectionClass(static::class);
函数 getConstants()
返回名称/值映射,而 getConstant($name)
仅返回其值。两者都不返回可见性信息。难道不应该有一个类似于函数、属性等的 ReflectionConst
类吗?
还有其他方法可以获取这些信息吗?
最佳答案
the feature's RFC 中涉及了对此的反射更改,尽管我不知道它们是否已在其他地方记录下来。
新类是 ReflectionClassConstant
,具有相关方法(除其他外):
isPublic()
isPrivate()
isProtected()
ReflectionClass
有两个新方法:
getReflectionConstants()
- 返回 ReflectionClassConstants 数组getReflectionConstant()
- 按名称检索 ReflectionClassConstant
示例:
class Foo
{
private const BAR = 42;
}
$r = new ReflectionClass(Foo::class);
var_dump(
$r->getReflectionConstants(),
$r->getReflectionConstant('BAR')->isPrivate()
);
输出:
array(1) {
[0]=>
object(ReflectionClassConstant)#2 (2) {
["name"]=>
string(3) "BAR"
["class"]=>
string(3) "Foo"
}
}
bool(true)
关于reflection - 在 PHP 中获取 const 可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44947797/