Here, we will call the constructor of the parent class from the constructor of the child class, here we need to use the parent keyword with :: (scope resolution operator).
The source code to call the base class constructor from the derived class is given below. The given program is compiled and executed successfully.
<?php
//PHP program to call a base class constructor
//from the derived class.
class Base
{
function __construct()
{
echo "Base:constructor called<br>";
}
}
class Derived extends Base
{
function __construct()
{
parent::__construct();
echo "Derived:constructor called<br>";
}
}
$dObj = new Derived();
?>
Output:
Base:constructor called
Derived:constructor called
Explanation:
In the above program, we created two classes Base and Derived. Here, we inherited the Base class into the derived class using the extends keyword.
Both Base and Derived classes contain constructors. Here, we called the parent class constructor from the child class constructor using the parent keyword.
At last, we created the object $dObj of Derived class then the constructor of the derived class gets called that will call the constructor of Base class using parent keyword that will print the appropriate message on the webpage.
Program/Source Code:
The source code to call the base class constructor from the derived class is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two classes Base and Derived. Here, we inherited the Base class into the derived class using the extends keyword.
Both Base and Derived classes contain constructors. Here, we called the parent class constructor from the child class constructor using the parent keyword.
At last, we created the object $dObj of Derived class then the constructor of the derived class gets called that will call the constructor of Base class using parent keyword that will print the appropriate message on the webpage.