Php,即使使用反射,我也无法访问继承的私有变量 [英] Php, I cant access inherited private variables not even with reflection
本文介绍了Php,即使使用反射,我也无法访问继承的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A
{
private $a;
}
class B extends A
{
function __construct()
{
(new \ReflectionClass($this))->getProperty('a')->setAccessible(true);
echo $this->a;
}
}
(new B());
这应该可以工作,尽管它会触发异常:属性 a 不存在".很多文章都说反射是解决方案
this should work, altough it triggers an exception: "property a doesnt exists". Many articles says Reflection is the sollution
推荐答案
您正在向 ReflectionClass
传递一个 B
的实例,该实例无权访问 <代码>$a.您需要的是将 A
的实例传递给它.这应该有助于澄清您需要在这里做什么
You're passing the ReflectionClass
an instance of B
, which doesn't have access to $a
. What you need is to pass it an instance of A
instead. This should help clarify what you need to do here
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());
这篇关于Php,即使使用反射,我也无法访问继承的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文