Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

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?

like image 726
Blip Avatar asked Oct 25 '16 15:10

Blip


1 Answers

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

like image 71
Machavity Avatar answered Nov 15 '22 02:11

Machavity