我有个抽象的课程
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()。
发布于 2013-07-14 08:14:04
事实并非如此。
当我运行上面给出的代码时,我得到了以下输出:
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-14 08:29:11
谢谢@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对象调用了抽象构造函数。
https://stackoverflow.com/questions/17637642
复制相似问题