How to Call Parent Class Constructor in PHP

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.

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.

Subscribe Our Tutorials

Get Latest Updates on Facebook

2. ┬áLet’s check another scenario.

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

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.

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.