实例化派生类时是否隐式调用抽象类构造函数?
举个例子:
abstract class Base {
function __construct() {
echo 'Base __construct<br/>';
}
}
class Child extends Base {
function __construct() {
echo 'Child __construct<br/>';
}
}
$c = new Child();
我有 C# 背景,我期望输出是
基础 __construct
子 __construct
然而,实际输出只是
子__construct
Take this example:
abstract class Base {
function __construct() {
echo 'Base __construct<br/>';
}
}
class Child extends Base {
function __construct() {
echo 'Child __construct<br/>';
}
}
$c = new Child();
Coming from a C# background, I expect the output to be
Base __construct
Child __construct
However, the actual output is just
Child __construct
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,如果子类定义了构造函数,则不会调用父类的构造函数。
从子类的构造函数中,您必须调用父类的构造函数:
如果需要,向其传递参数。
通常,您将在子类的构造函数的开头、任何特定代码之前执行此操作;这意味着,就您而言,您将拥有:
并且,作为参考,您可以查看 PHP 手册的此页面:构造函数和析构函数 - 它指出(引用):
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 :
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 :
And, for reference, you can take a look at this page of the PHP manual : Constructors and Destructors -- it states (quoting) :
好吧,我刚刚在文档中找到了这个:
Well, I just found this in the docs:
如果您需要与 C# 相同的行为,即父构造函数始终在子构造函数之前执行,您可以为子类创建一个假构造函数类,并将其声明为抽象父类中的抽象函数。
例如
If you need the same behaviour as C#, that is the parent constructor gets always executed before child constructor, you could create a fake constructor class for your child classes and declare it as an abstract function in your abstract parent class.
E.g.