PHP在子类覆盖父类变量后如何通过扩展类访问父类变量

4

如果子类继承后覆盖了父类的变量,我们如何通过子类访问原始的父类变量?

class SimpleClass{
    public $var = 'This is Parent';

    public function getVar(){
        return $this->var;
    }
}

class ExtendClass extends SimpleClass{
    public $var = 'This is Child';

    public function getParent(){
        return parent::getVar();
    }
}

$obj = new ExtendClass();

echo $obj->getParent(); // Prints 'This is Child'

I'm sure it has something to do something with $this pseudo-variable, because i'm constructing ExtendClass, in that context $this only have access to the overridden $var variable.

So i tried to statically access the variable through class methods.

class SimpleClass{
    public static $var = 'This is Parent';

    public function getVar(){
       return self::$var;
    }
}

class ExtendClass extends SimpleClass{
    public static $var = 'This is Child';

    public function getParentVar(){
        return parent::getVar();
    }

    public function getChildVar(){
        return self::$var;
    }
}

$obj = new ExtendClass();

echo $obj->getParentVar();// Prints 'This is Parent'

echo $obj->getChildVar();// Print 'This is Child'

It worked, but how can we non-statically access the parent class variable through getVar() method of Parent class.


我不明白为什么你需要在两个类中使用相同的变量名。简单来说,只保留一个变量名称。如果你需要两个变量,则使用两个变量名。 - Shaiful Islam
你想访问默认值吗?否则就没有意义了,因为在对象上下文中,父实例与子实例不会真正有所不同。 - Michael Berkowski
1个回答

2

除非子类在编辑之前明确地备份原始值,否则您无法访问类成员的父级值,因为不存在父级值。子类和父类的代码共享相同的变量。


2
你可以使用 ReflectionClass 来检索它的默认值,但这是另一个完全不同的问题。 - Michael Berkowski
@MichaelBerkowski 嗯,我没有仔细阅读问题。在这种情况下 - 在类头中声明一个显式的默认值 - 反射是答案。为什么不准备一个例子呢?... - hek2mgl
1
我正在向OP澄清,并且如果确实需要的话,将会发布一个答案。 - Michael Berkowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接