例如,如果我有这段代码:
class a {
function __construct() {
echo "hello";
}
class b extends a{
function __construct() {
echo "world";
}
}
我希望它输出“Hello World”。相反,A类构造函数被B类构造器覆盖,因此仅输出“world”。
答案 0 :(得分:5)
使用此:
class a {
public function __construct(){
echo "hello";
}
}
class b extends a {
public function __construct(){
parent::__construct(); // this line calls the parent (a) constructor
echo "world";
}
}
PHP Constructors and Destructors doc州:
注意:如果子类,则不会隐式调用父构造函数 定义构造函数。为了运行父构造函数,调用 子构造函数中的parent :: __ construct()是必需的。如果 child没有定义构造函数,那么它可能会继承自 父类就像普通的类方法(如果它没有声明 作为私人)。
答案 1 :(得分:0)
,在echo之前调用类a的构造函数。
parent::__construct();