
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call Parent Constructor in Child Class in PHP
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
<?php class grandpa{ public function __construct(){ echo "I am in Tutorials Point"."
"; } } 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
<?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.
Advertisements