Monday, December 15, 2014

How to Call Parent Class Constructor in PHP

We got an introduction about the constructor in PHP 5. Constructors are magic method which call automatically when an object is created but when you define the constructor method both in Child and Parent class, it will not call until you explicitly reference it. So let's check how to call parent class constructor in child class.


Check out the below code :-

class BaseClass {

  public function __construct(){

         echo "parent";
   }

}

/* Inherits Parent Class. */
class ChildClass extends BaseClass{

}

/* Let's check what's happen if i create an object of child class. */

$obj = new ChildClass;

// Prints Parent

Here, you can see two classes BaseClass and ChildClass. ChildClass inherits BaseClass. In BaseClass Constructor is already defined and child does not have any constructor method. When I create an object of ChildClass it will print whatever written in BaseClass constructor.

 Let’s check another example.

<?php

class BaseClass {

  public function __construct(){

         echo "parent";
  }

}

class ChildClass extends BaseClass{

  public function __construct(){

        echo "child";
  }

}

$obj = new ChildClass;

// Prints child

In above code,  ChildClass constructor override BaseClass constructor. The BaseClass constructor is not called unless you explicitly reference it.

How to Call Parent Class Constructor in PHP

You can call parent class constructor in child class by parent::__construct() .

class ChildClass extends BaseClass{

  public function __construct(){

        /* Calling parent class constructor. */
        parent::__construct();
        echo "child";
  }

}

$obj = new ChildClass;

/* Prints parent and child both. */

Reference: http://studentduniya.in/call-parent-class-constructor-php/

0 comments:

Post a Comment