BenMorel
BenMorel

Reputation: 36484

Access child property with conflicting name from parent class in PHP

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?

Upvotes: 3

Views: 1014

Answers (1)

netcoder
netcoder

Reputation: 67695

Normally, you can't. You would have to declare A::$n protected or public, because private members always have precedence. If you declare A::$n public, then B::$n will 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:

abstract class A {
    private $n = 1;

    public function getN() {
        $ref = new ReflectionProperty($this, 'n');
        $ref->setAccessible(true);
        echo $ref->getValue($this);
    }
}

class B extends A {
    protected $n = 2;
}

$b = new B;
echo $b->getN(); // 2

Upvotes: 3

Related Questions