Reputation: 6197
class A
{
private $a;
}
class B extends A
{
function __construct()
{
(new \ReflectionClass($this))->getProperty('a')->setAccessible(true);
echo $this->a;
}
}
(new B());
this should work, altough it triggers an exception: "property a doesnt exists". Many articles says Reflection is the sollution
Upvotes: 1
Views: 97
Reputation: 92854
I cant access inherited private variables not even with reflection
Private properties and methods belong to a class they were declared.
They're not accessible from the derived class unless you override them
Upvotes: 1
Reputation: 31624
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());
Upvotes: 2