检测受保护的方法并避免致命错误


detect protected method and avoid fatal error

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

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

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

我的工作:

$foo=new foo();$reflect=新的ReflectionClass($foo);$props=$reflect->getProperties(反射属性::IS_PUBLIC|反射属性:IS_PROTECTED);foreach($props作为$prop){打印$prop->getName()。"''n";}

然而,有些类确实有受保护的方法,例如:

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

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

致命错误:从[path/gos/here]中的上下文"View"调用受保护的Foo::__construct()

最好的办法是什么?(如果有)

更改

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

$reflect = new ReflectionClass('Foo');

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

如果使用protectedprivate,则无法从类外部访问构造函数。

调用$foo = new Foo();将引发错误。

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