如果子类继承后覆盖了父类的变量,我们如何通过子类访问原始的父类变量?
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.