Is it mandatory to call parent::__construct from t

2019-05-09 13:45发布

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 :

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. But can these be done in PHP?

2条回答
放我归山
2楼-- · 2019-05-09 13:53

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

查看更多
3楼-- · 2019-05-09 14:05

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. 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.

查看更多
登录 后发表回答