从PHP的子类的构造函数中调用parent :: __ construct是强制性的吗? [英] Is it mandatory to call parent::__construct from the constructor of child class in PHP?
问题描述
是否必须从子类构造函数中的构造函数调用父构造函数?
Is it mandatory to call the parent's constructor from the constructor in the child class constructor?
为说明原因,请考虑以下示例:
To explain consider the following example:
class Parent{
function __construct(){
//something is done here.
}
}
class Child extends Parent{
function __construct(){
parent::__construct();
//do something here.
}
}
如上所述,这样做是很正常的.但是请考虑以下 Child
类的构造函数:
This is quite normal to do it as above. But consider the following constructors of the class Child
:
function __construct(){
//Do something here
parent::__construct();
}
以上代码正确吗?在调用父级的构造函数之前,我们可以做些什么吗?另外,如果我们不像下面那样在子代的构造函数中调用父代的构造函数,这合法吗?
Is the above code correct? Can we do something before you call the parent's constructor? Also if we do not call the parent's constructor in the child's constructor like below is it legal?
class Child extends Parent{
function __construct(){
//do something here.
}
}
我来自JAVA,而我展示的构造函数类型在Java中是不可能的.但是这些可以用PHP完成吗?
I am from JAVA, and the types of constructor I have shown are not possible in Java. But can these be done in PHP?
推荐答案
这是强制性的吗?
Is it mandatory?
否
以上代码正确吗?
Is the above code correct?
是
在调用父级的构造函数之前,我们可以做些什么吗?
Can we do something before you call the parent's constructor?
是的.您可以按任意顺序进行操作.
Yes. You can do it in any order you please.
如果我们不像下面那样在子代的构造函数中调用父代的构造函数,这合法吗?
Also if we do not call the parent's constructor in the child's constructor like below is it legal?
是的.但这也不是隐式.如果子构造函数没有调用父构造函数,则它将永远不会被调用,因为子构造函数会覆盖父构造函数.如果您的孩子没有构造函数,那么将使用父构造函数
Yes. But it's not implicit either. If the child constructor doesn't call the parent constructor then it will never be called because the child constructor overrides the parent. If your child has no constructor then the parent constructor will be used
这篇关于从PHP的子类的构造函数中调用parent :: __ construct是强制性的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!