How to call parent constructor in child class in PHP?

Object Oriented ProgrammingPHPProgramming

We will face two cases while calling the parent constructor method in child class.

Case1

We can't run directly the parent class constructor in child class 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.

Example

 Live Demo

<?php
   class grandpa{
      public function __construct(){
         echo "I am in Tutorials Point"."\n";
      }
   }
   class papa extends grandpa{
      public function __construct(){
         parent::__construct();
         echo "I am not in Tutorials Point";
      }
   }
$obj = new papa();
?>
Output:
I am in Tutorials Point
I am not in Tutorials Point

Explanation

In the above example, we have used parent::__construct() to call the parent class constructor.

Case2

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

Example

 Live Demo

<?php
   class grandpa{
      public function __construct(){
         echo "I am in Tutorials point";
      }
   }
   class papa extends grandpa{
   }
   $obj = new papa();
?>

Output

I am in Tutorials point

Explanation

Here the parent class is called implicitly because in child class we have not declared any constructor function in child class.

raja
Published on 25-Jun-2019 17:31:51
Advertisements