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

时间:2013-01-17 00:53:39

标签: php object

以下代码给出了错误

class One{    
    public $var = 10;
}

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

$two = new Two();
echo $two->var;

4 个答案:

答案 0 :(得分:1)

您正在覆盖您的变量。如果您需要在抽象/父类中使用某种默认/只读,请尝试以下方法:

<?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;

?>

答案 1 :(得分:1)

如果您希望得到这样的parent::$var(如此静态),请将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;

答案 2 :(得分:0)

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

class One {
    public $var = 10;
}

class Two extends One {
}

$two = new Two();
echo $two->var;

答案 3 :(得分:0)

只要变量是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