reflection - 在 PHP 中获取 const 可见性

标签 reflection php-7.1

从 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/

相关文章:

java - 用于复杂对象的 apache EqualsBuilder

macos - 无法通过 Homebrew 软件安装php7或php 7.1

mysql - 如何在数据透视表字段中进行求和并在 yajra-laravel-datatable 包中搜索该字段(laravel 5.6)

PHP 7.1 Doctrine 代理问题与可空类型

php - 使用 PHP 在 FTP 服务器上创建文件夹

ruby - 是否有可能获得 Ruby 中的所有特征类?

c# - 在 C# 中使用反射初始化 IEnumerable 属性 (propertyInfo)

java - 可以覆盖 Set 的 contains() 方法吗?

c# - 获取特定类中使用的类型

jenkins - PHP 启动 : Unable to load dynamic library '/usr/lib/php/20160303/pdo_sqlite.so' with Jenkins