实例化派生类时,是否不会隐式调用抽象类构造函数? [英] Are abstract class constructors not implicitly called when a derived class is instantiated?
问题描述
以这个例子为例:
abstract class Base {
function __construct() {
echo 'Base __construct<br/>';
}
}
class Child extends Base {
function __construct() {
echo 'Child __construct<br/>';
}
}
$c = new Child();
来自 C# 背景,我希望输出是
Coming from a C# background, I expect the output to be
基础__construct
子__construct
Base __construct
Child __construct
然而,实际输出只是
子 __construct
Child __construct
推荐答案
否,如果子类定义了构造函数,则不会调用父类的构造函数.
No, the constructor of the parent class is not called if the child class defines a constructor.
从你的子类的构造函数中,你必须调用父类的构造函数:
From the constructor of your child class, you have to call the constructor of the parent's class :
parent::__construct();
如果需要,传递它的参数.
Passing it parameters, if needed.
通常,您会在子类的构造函数的开头、任何特定代码之前执行此操作;这意味着,在您的情况下,您将有:
Generally, you'll do so at the beginning of the constructor of the child class, before any specific code ; which means, in your case, you'd have :
class Child extends Base {
function __construct() {
parent::__construct();
echo 'Child __construct<br/>';
}
}
而且,作为参考,您可以查看 PHP 手册的这一页:Constructors和析构函数——它声明(quoting) :
注意:如果子类不隐式调用父构造函数定义一个构造函数.
为了运行父构造函数,调用parent::__construct()
在子构造函数是必需的.
Note: Parent constructors are not called implicitly if the child class defines a constructor.
In order to run a parent constructor, a call toparent::__construct()
within the child constructor is required.
这篇关于实例化派生类时,是否不会隐式调用抽象类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!