Search code examples
phpattributesparent

Access parent value


I have the following scenario:

class ClassA {
    protected $attr1 = 'value1';

    public function getAttr() {
        return $this->attr1;
    }
}

class ClassB extends ClassA {
    protected $attr1 = 'value2';

    public function getParentAttr() {
        return parent::getAttr();
    }
}

$object = new ClassB();
echo $object->getParentAttr(); //prints 'value2' instead of 'value1'

Is there a way to make getParentAttr return the default value of the parent's property, as its declared in ClassA?

I've tried to return self::$attr1 in getAttr method but it throws an undeclared static property error.


Solution

  • You cannot do that by default and you should not in most cases. Anyway there are apparently two ways to achieve it.

    1. Using a new instance

    The easiest way is to create a new instance of the class and get the value from there. This might however have sideeffects and may not be possible in some cases.

    2. Using Reflection

    You can get the default values of a property using reflection.

    $refl = new ReflectionClass("ClassA");
    var_dump($refl->getDefaultProperties());
    

    Which should result in:

    array(1) {
        ["attr1"]=>
        string(6) "value1"
    }