0

is there any work around to access the parents values that ware overwritten by child?

parent::$prop: expect to be static. and the same with: self::$prop

    class base {

    public $name = 'base';

    public function __construct()
    {

        echo $this->name . "\n";
        echo self::$name . "\n";

    }

}

class sub extends base {

    public $name = 'sub';

    public function __construct()
    {
        parent::__construct();     // output: sub
                                   // Fatal error

        echo $this->name . "\n";   // output: sub
        echo parent::$name . "\n"; // Fatal error

    }

}

new sub();
learning php
  • 1,134
  • 2
  • 10
  • 14
  • $name in base is not static, so you cannot access it self::$prop, also, when you're declaring non static variable with the same name as parent's one - it will be overwritten and there is no access to base one – Iłya Bursov Oct 23 '13 at 06:31

1 Answers1

1

I don't know is this the best way but it works. For more information you may look at the link: http://www.php.net/manual/en/ref.classobj.php

public function __construct()
{
    parent::__construct();     // output: sub
    echo $this->name . "\n";   // output: sub
    echo $this->getParentProp('name'); //output: base
}

public function getParentProp($name)
{
     $parent = get_class_vars(get_parent_class($this));
     return $parent[$name];
}
draconis
  • 458
  • 5
  • 16