构造函数参数不会继承到子项?

时间:2015-06-01 10:06:12

标签: php oop inheritance constructor

我是php的新手,尤其是oop。我有这段测试代码,我认为会返回:

What is the result?8
What is the result?8

但是,相反,我得到了:

What is the result?5
What is the result?8

传递给类实例的参数似乎没有被分配给x。我也尝试过echo $second->x而不返回任何内容。

我是否有一些错误的代码,我是否误解了继承问题,或者我误解了constructors的某些内容?

以下是代码:

<?php
class First{
    public function __construct($x){
        $this->x = $x;
        echo "What is the result?";
    }
}                                    

class Second extends First{
    public function calculation(){
        $z=5;
        return $x+$z."<br />";
    }
}

class Third extends First{
    public function calculation(){
        $z=5;
        $x=3;
        $y=$x+$z;
        return $y."<br/>";
    }
}

$second = new Second('3');
echo $second->calculation();
$third = new Third('3');
echo $third->calculation();
?>

2 个答案:

答案 0 :(得分:1)

如果覆盖方法,就像本例中的构造函数一样,则需要显式调用父类方法,如下所示:

class A {
    public function __construct() {
        var_dump(__METHOD__);
    }
}

class B extends A {
    public function __construct() {
        var_dump(__METHOD__);
        // call parent constructor
        parent::__construct();
    }
}

$b = new B();

输出:

string(14) "B::__construct"
string(14) "A::__construct"

答案 1 :(得分:1)

Second班级

内进行少量更新
class Second extends Test{
    public function calculation(){
        $z=5;
        return $this->x+$z."<br />";//$x  should be $this->x
    }
}

<强>输出:

What is the result?8
What is the result?8