【问题标题】:php - detect protected method and avoid fatal errorphp - 检测受保护的方法并避免致命错误
【发布时间】:2014-12-21 08:46:39
【问题描述】:

我必须从存储在一个目录中的多个类中获取属性。

我收集受保护和公共财产没有问题。

我只在公开之后,所以到目前为止一切都很好。

我做什么:

$foo = 新的 Foo(); $reflect = new ReflectionClass($foo); $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); foreach ($props 作为 $prop) { 打印 $prop->getName() 。 "\n"; }

但是,某些类确实具有受保护的方法,例如:

类Foo { 公共 $foo = 1; 受保护的 $bar = 2; 私人 $baz = 3; 受保护的函数 __construct() { } }

一旦我遇到这样的课程,我就会遇到一个致命错误,这会阻碍我的努力:

致命错误:从 [path/goes/here] 中的上下文“视图”调用受保护的 Foo::__construct()

最好的解决方法是什么? (如果有的话)

【问题讨论】:

    标签: php oop reflection methods properties


    【解决方案1】:

    改变

    $foo = new Foo();
    $reflect = new ReflectionClass($foo);
    

    $reflect = new ReflectionClass('Foo');
    

    如果你真的想创建一个新实例,请查看newInstanceWithoutConstructor 函数

    【讨论】:

      【解决方案2】:

      如果您使用protectedprivate,那么您的构造函数将无法从类外部访问。

      调用$foo = new Foo(); 会抛出错误。

      $reflect = new ReflectionClass('Foo');
      echo $reflect->getName();// output Foo
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 2016-07-23
        • 1970-01-01
        相关资源
        最近更新 更多