0

我有这个抽象类

 abstract class Guitar {

        protected $strings;

        public function __construct($no_of_strings) {
            $this->strings = $no_of_strings;
            echo 'Guitar class constructor is called <br/>';
        }

        abstract function play();
    }

还有儿童班,

class Box_Guitar extends Guitar {

    public function __construct($no_of_strings) {
        echo 'Box Guitar constructor is called <br/>';
        $this->strings = $strings + 100;
    }

    public function play() {
        echo 'strumming ' . $this->strings;
    }

}

然后我开始上课,

$box_guitar = new Box_Guitar(6);

我的输出是

Box Guitar 构造函数被调用

吉他类构造函数被调用

弹奏 106

所以我的问题是为什么要调用父构造函数?我没有使用 Parent::__construct()。

4

2 回答 2

1

它不是。

当我运行你上面给出的代码时,我得到这个输出:

调用 Box Guitar 构造函数
注意:未定义变量:第 19 行 /test/test.php 中的字符串

仔细检查您没有运行旧版本的文件或其他东西。您是否忘记保存或上传一些更改?


作为记录,一旦您弄清楚为什么会出现意外行为,编写Box_Guitar构造函数的正确方法可能如下所示:

public function __construct($no_of_strings) {
    echo 'Box Guitar constructor is called <br/>';
    parent::__construct($no_of_strings + 100);
}
于 2013-07-14T08:14:04.100 回答
0

谢谢@jcsanyi。是我的错。我还有一堂课叫,

 class Electric_Guitar extends Guitar {

    public function play() {
        return 'Plug to current : '. $this->strings;
    }
}

这没有任何构造函数。当我调用对象时,我使用了它们。

$box_guitar = new Box_Guitar(6);
$elec_guitar = new Electric_Guitar(5);

所以抽象构造函数被 elec_guitar 对象调用。

于 2013-07-14T08:29:11.403 回答