When both a parent class (superclass) and a child class (subclass) have constructors (__construct() methods) Then Which Call First During Object Creation.

In PHP, when both a parent class (superclass) and a child class (subclass) have constructors (__construct() methods), the constructor of the child class will override the constructor of the parent class. However, the constructor of the parent class can still be explicitly called from the constructor of the child class using the parent::__construct() syntax.

Let’s illustrate this with an example:

class ParentClass {
    public function __construct() {
        echo "Parent constructor<br>";
    }
}

class ChildClass extends ParentClass {
    public function __construct() {
        echo "Child constructor<br>";
        parent::__construct(); // Calling parent class constructor
    }
}

// Creating an object of the child class
$object = new ChildClass();

Output:

Child constructor
Parent constructor

Explanation:

  • When an object of the ChildClass is created, PHP automatically calls the constructor of the child class (Child constructor).
  • Inside the constructor of the child class, we explicitly call the constructor of the parent class using parent::__construct(). This results in the output of Parent constructor.
  • If we don’t explicitly call parent::__construct(), the constructor of the parent class will not be executed.

In summary, when both the parent and child classes have constructors, the constructor of the child class will be called by default. However, you can explicitly call the constructor of the parent class from within the constructor of the child class if needed.

Related Posts

Leave A Comment