-3

以下代码给了我一个错误

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

4 回答 4

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;

?>
于 2013-01-17T01:02:11.897 回答
1

如果你想得到这样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;
于 2013-01-17T01:25:00.607 回答
0

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

class One {
    public $var = 10;
}

class Two extends One {
}

$two = new Two();
echo $two->var;
于 2013-01-17T00:56:25.070 回答
0

只要变量是publicor protected,它就会被子类继承。

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
于 2013-01-17T01:03:29.043 回答