【问题标题】:Get const visibility in PHP在 PHP 中获取 const 可见性
【发布时间】:2017-07-06 11:37:10
【问题描述】:

从 PHP 7.1 开始,他们引入了 const 可见性,我需要通过反思来阅读它。我什至像这样创建我的ReflectionClass

$rc = new ReflectionClass(static::class);

函数getConstants() 返回一个名称/值映射,getConstant($name) 只是它的值。两者都不返回可见性信息。不应该有一个类似于函数、属性等的ReflectionConst 类吗?

还有其他方法可以获取这些信息吗?

【问题讨论】:

    标签: reflection php-7.1


    【解决方案1】:

    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)
    

    【讨论】:

    猜你喜欢
    • 2011-06-10
    • 2010-11-20
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 2012-08-01
    • 2010-09-18
    • 2015-10-18
    • 1970-01-01
    相关资源
    最近更新 更多