Is it possible to access a child property from a parent class, when both parent and child share the same property name, but with different visibility?
Consider the following example:
abstract class A {
private $n = 1;
public function getN() {
return $this->n;
}
}
class B extends A {
protected $n = 2;
}
$b = new B;
echo $b->getN(); // returns 1
getN() returns 1, because it returns the value of its own private $n.
Is it possible to get the value of the child’s protected $n instead, from the parent?
Normally, you can’t. You would have to declare
A::$nprotectedorpublic, because private members always have precedence. If you declareA::$npublic, thenB::$nwill also need to be public, since you cannot override a property with less visibility than its parent. You can do it only by using the Reflection API: