
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to 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"."\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
<?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.
- Related Questions & Answers
- How to explicitly call base class constructor from child class in C#?
- How to call the constructor of a parent class in JavaScript?
- How to call a parent class function from derived class function in C++?
- Why static methods of parent class gets hidden in child class in java?
- How to call Private Constructor in Java
- Instance child class in abstract static method PHP?
- jQuery parent > child Selector
- Can we define constant in class constructor PHP?
- How can we call one constructor from another in the same class in C#?
- How to call one constructor from another in Java?
- How to call the constructor of a superclass from a constructor in java?
- How to remove all child nodes from a parent in jQuery?
- How to generate child keys by parent keys in array JavaScript?
- How to call a static constructor or when static constructor is called in C#?
- Are the private variables and private methods of a parent class inherited by the child class in Java?
Advertisements