如何从扩展类访问父类的变量


How to access variables of parent class from extended class?

下面的代码给出了一个错误

class One{    
    public $var = 10;
}
class Two extends One{
    public $var = 20;
    function __construct(){
        $this->var = parent::$var;
    }
}
$two = new Two();
echo $two->var;

如果您想获得这样的parent::$var(如此静态),则在One和Two中将var定义为static

class One {    
    public static $var = 10;
}
class Two extends One {
    public static $var = 20;
    public function __construct() {
        // this line creates a new property for Two, not dealing with static $var
        $this->var = parent::$var;
        // this line makes real change
        // self::$var = parent::$var;
    }
}
$two = new Two();
echo $two->var; // 10
echo $two::$var; // 20, no changes
echo Two::$var;  // 20, no changes
// But I don't recommend this usage
// This is proper for me; self::$var = parent::$var; instead of $this->var = parent::$var;

您正在重写变量。如果您需要在抽象/父类中设置某种默认/只读类型,请尝试这样做:

<?php
class One{    
    private $var = 10;
        public function getVar(){
            return $this->var;
        }
}
class Two extends One{
    public $var;
    function __construct(){
        $this->var = parent::getVar();
    }
}
$two = new Two();
echo $two->var;
?>

这是内置的;只是不要重新声明变量。(演示)

class One {
    public $var = 10;
}
class Two extends One {
}
$two = new Two();
echo $two->var;

只要变量是publicprotected,那么它将被子类继承。

class One{    
    public $var = 10;
}
class Two extends One{
    public $var = 20;
}
class Three extends One{
}
$a = new One();
echo $a->var; // 10
$b = new Two();
echo $b->var; // 20
$c = new Three();
echo $c->var; // 10