PHP 5 introduced the concept of constructor. Constructors are magic method which call automatically when 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 How to call parent class constructor in child class.
Let’s check some code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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 i have created two classes BaseClass and ChildClass. ChildClass inherits BaseClass. In BaseClass i haved defined constructor and child does not have any constructor method. So when i create an object of ChildClass it will print whatever written in BaseClass (parent class) constructor.
2. Let’s check another scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php class BaseClass { public function __construct(){ echo "parent"; } } class ChildClass extends BaseClass{ public function __construct(){ echo "child"; } } $obj = new ChildClass; // Prints child |
In this case, ChildClass constructor override BaseClass constructor. The BaseClass (parent class) 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() .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class ChildClass extends BaseClass{ public function __construct(){ /* Calling parent class constructor. */ parent::__construct(); echo "child"; } } $obj = new ChildClass; /* Prints parent and child both. */ |
NOTE : When you override any parent class method by defining one in the child class, the parent method isn’t called unless you explicitly reference it by parent::methodname.