Call Parent Class construct Before Child’s In PHP

PHP

Read {count} times since 2020

If in PHP, you are making a child class of a parent class in which both have the __construct function and you want to call both of them when the child object is made, it won’t work.

This is because, when you make the child class object, it’s construct function is called. The parent’s construct function is being overridden by the child. The PHP manual on OOP (Object Oriented Programming) notes this :

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

So, the parent’s construct function is not called if w’re making the child object.

Classes

This is the parent class named “MyParentClass” :

class MyParentClass {
 public $myVal = 0;
 function __construct(){
  $this->myVal = 1;
 }
}

And we extend it to make the child class named “MyChildClass” :

class MyChildClass extends MyParentClass {
 function __construct(){
  echo $this->myVal;
 }
}

Now, when you make the child object, the output made by echo will be nothing but **** :

new MyChildClass()

(We’re using direct echo and not return).

Reason

In the parent class, we make a public variable called “myVal” which is set to 0. When the parent class is made by this :

new MyParentClass()

the value of MyParentClass::myVal is changed to “1”. This change only takes effect if the parent class is made and not the child class. So, when you make the child class, the output will be **** and not 1.

Solution

But, you can also make changes first in the parent class and then do the code in MyChildClass::__construct(). For this, we add the following code as the first code in MyChildClass::__construct() :

parent::__construct();

And the whole child class will become :

class MyChildClass extends MyParentClass {
 function __construct(){
  parent::__construct();
  echo $this->myVal;
 }
}

Don’t be worried about the constant parent, because it’s built in and it defines the parent class from which we are extending the main class.

Now, when you make the child class, the output will be 1 because the parent __construct() is called before the code in child’s __construct() is ran.

You can apply the same solution in your child classes, so that parent and class is linked instead of going separate ways.