它似乎不起作用:
$ref = new ReflectionObject($obj);
if($ref->hasProperty('privateProperty')){
print_r($ref->getProperty('privateProperty'));
}
它进入 IF 循环,然后抛出错误:
属性 privateProperty 不存在
:|
$ref = new ReflectionProperty($obj, 'privateProperty')
也不起作用...
The 文档页 http://www.php.net/manual/en/class.reflectionproperty.php列出了一些常量,包括IS_PRIVATE
。如果我无法访问私有财产,我该如何使用它呢?
class A
{
private $b = 'c';
}
$obj = new A();
$r = new ReflectionObject($obj);
$p = $r->getProperty('b');
$p->setAccessible(true); // <--- you set the property to public before you read the value
var_dump($p->getValue($obj));
Update:从 PHP 8.1.0 开始,调用ReflectionProperty::setAccessible https://www.php.net/manual/en/reflectionproperty.setaccessible.php方法没有效果;默认情况下可以访问所有属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)