Php 重写的抽象类构造函数
我有一个抽象类Php 重写的抽象类构造函数,php,oop,abstract-class,Php,Oop,Abstract Class,我有一个抽象类 abstract class Guitar { protected $strings; public function __construct($no_of_strings) { $this->strings = $no_of_strings; echo 'Guitar class constructor is called <br/>'; }
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();
}
我的出局是
盒吉他构造函数被调用
吉他类构造函数被称为
弹奏106
所以我的问题是为什么调用父构造函数?我没有使用Parent::\u construct()。不是
当我运行上面给出的代码时,我得到以下输出:
盒吉他构造函数被称为注意:未定义变量:第19行/test/test.php中的字符串 再次检查您是否正在运行旧版本的文件或其他内容。您是否忘记保存或上载一些更改
作为记录,一旦你弄清楚了为什么会出现这种意外行为,编写
Box\u guist
构造函数的正确方法可能如下所示:
public function __construct($no_of_strings) {
echo 'Box Guitar constructor is called <br/>';
parent::__construct($no_of_strings + 100);
}
public function\u构造($no\u of\u字符串){
echo“盒吉他构造函数被称为
”;
父项::__构造($no_of_字符串+100);
}
谢谢@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_吉他对象调用了abstrct构造函数
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);