简体   繁体   English

是否必须从PHP中的子类的构造函数中调用parent :: __构造?

[英]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.
    }

}

This is quite normal to do it as above. 如上所述这是很正常的。 But consider the following constructors of the class Child : 但请考虑以下类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.
    }

}

I am from JAVA, and the types of constructor I have shown are not possible in Java. 我来自JAVA,我所展示的构造函数类型在Java中是不可能的。 But can these be done in PHP? 但这些可以在PHP中完成吗?

Is it mandatory? 这是强制性的吗?

No 没有

Is the above code correct? 以上代码是否正确?

Yes

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 如果您的孩子没有构造函数,那么将使用父构造函数

No, it is not mandatory to call the parent constructor, but if the parent constructor has side-effects that the child class should also have then it would be good. 不,调用父构造函数并不是必须的,但如果父构造函数具有子类也应该具有的副作用,那么它将是好的。 See this phpfiddle where one sub-class calls the parent constructor but the other doesn't. 看到这个phpfiddle ,其中一个子类调用父构造函数,但另一个子类不调用。 So it is still valid code if the parent constructor is not called. 因此,如果未调用父构造函数,它仍然是有效的代码。

Also, if the constructor is not declared in the subclass (which would override the parent constructor), then the constructor from the parent class will be utilized. 此外,如果构造函数未在子类中声明(它将覆盖父构造函数),则将使用父类的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM