无论如何要访问被孩子覆盖的父属性?

时间:2013-10-23 06:06:50

标签: php subclass class-instance-variables

是否有任何解决方法可以访问由孩子覆盖的父级值?

parent :: $ prop:期望是静态的。和以下相同: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();

1 个答案:

答案 0 :(得分:1)

我不知道这是最好的方式,但它有效。有关详细信息,请查看链接: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];
}