如果子类没有定义构造函数,可以直接使用超类的构造函数吗?
构造函数是继承的还是属于定义它们的类?我只见过子类构造函数调用超类构造函数的示例。这是我当前的代码,它可以给出一些关于正在发生的事情的提示。 (我会根据你的回复更改代码。如果我可以使用超类的构造函数,我就不会为每个子类定义一个构造函数并从每个子类中调用超类的构造函数。
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
$this->viewerid = $viewerid;
}
Are constructors inherited or do they belong to the class they are defined in? I only have seen examples with constructors of subclasses which call superclass' constructors. This is my current code, which can give some hint about what's going on. (I will change the code according to your replies. If I can use the constructor of the superclass, I won't define a constructor for each subclass and call superclass' constructor from each.
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
$this->viewerid = $viewerid;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据我的理解,如果定义了子构造函数,PHP不会自动调用父构造函数。否则就是这样。
在子构造函数中,您必须手动调用父构造函数。
According to my understanding, PHP doesn't auto-call parent's constructor if child constructor is defined. Otherwise it does.
In child constructor you have to call parent's constructor manually.
parent::__construct(params);
用于调用超类构造函数构造函数
parent::__construct(params);
use for calling superclass constructorConstructors
如果子类定义了构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数中调用parent::__construct()。
参见此处
Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
See here