Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to call parent constructor in child class in PHP?
In PHP object-oriented programming, there are two scenarios when calling parent constructors in child classes, depending on whether the child class defines its own constructor.
Case 1: Child Class Has Its Own Constructor
When a child class defines its own constructor, the parent constructor is not automatically called. You must explicitly call parent::__construct() within the child constructor to execute the parent's initialization code ?
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials Point"."<br>";
}
}
class papa extends grandpa{
public function __construct(){
parent::__construct();
echo "I am not in Tutorials Point";
}
}
$obj = new papa();
?>
I am in Tutorials Point I am not in Tutorials Point
Explanation
In the above example, parent::__construct() explicitly calls the parent class constructor before executing the child's own constructor logic.
Case 2: Child Class Without Constructor
If the child class does not define a constructor, it automatically inherits the parent's constructor, just like any other non-private method ?
<?php
class grandpa{
public function __construct(){
echo "I am in Tutorials point";
}
}
class papa extends grandpa{
// No constructor defined
}
$obj = new papa();
?>
I am in Tutorials point
Explanation
Here the parent constructor is called automatically because the child class doesn't override it with its own constructor method.
Conclusion
Use parent::__construct() when your child class has its own constructor but still needs parent initialization. Without a child constructor, the parent constructor runs automatically through inheritance.
