The Complete Guide: Calling Parent Class Methods in PHP Inheritance
Last Updated: March 5, 2024
Understanding the Basics of PHP Inheritance
Inheritance in PHP allows classes to inherit properties and methods from another class. The class from which properties and methods are inherited is called the parent class, and the class that inherits those properties and methods is known as the child class. This relationship not only promotes code reusability but also helps in maintaining a clean and organized codebase.
Practical Example: Vehicular Actions
The Parent Class: Vehical
We start with a basic parent class named Vehical
, which includes methods to start and stop the engine:
class Vehical{
public function startEngine(){
echo "Engine started";
}
public function stopEngine(){
echo "Engine stopped";
}
}
Extending Functionality with the Car Class
To demonstrate the power of inheritance, we introduce a child class Car
that extends Vehical
:
class Car extends Vehical{
public function startEngine(){
// Calling the parent method
parent::startEngine();
echo "<br>Car engine started";
}
}
Demonstrating Inherited and Extended Behavior
When we instantiate the Car
class and call its methods, we observe the following:
$car = new Car();
$car->startEngine(); // Outputs: Engine started<br>Car engine started
$car->stopEngine(); // Outputs: Engine stopped