class A
{
private $a;
}
class B extends A
{
function __construct()
{
(new \ReflectionClass($this))->getProperty('a')->setAccessible(true);
echo $this->a;
}
}
(new B());
这应该可以工作,尽管它会触发异常:“属性 a 不存在”。很多文章都说反射是解决方案
你正在通过ReflectionClass
的一个实例B
,无权访问$a
。你需要的是传递一个实例A
反而。这应该有助于澄清您需要在这里做什么
class A
{
private $a = 'Bob';
}
class B extends A
{
function __construct()
{
$instance = new A();
$reflection = new \ReflectionClass($instance);
$property = $reflection->getProperty('a');
$property->setAccessible(true);
echo $property->getValue(new A());
}
}
(new B());
Demo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)