What is Inheritance in PHP?
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and behavior of another class. In PHP, inheritance is used to create a new class based on an existing class, promoting code reusability and modularity.
Benefits of Inheritance in PHP
The main benefits of using inheritance in PHP include code reusability, easier maintenance, and improved readability. By inheriting the properties and methods of a parent class, a child class can build upon the existing functionality, reducing the need to duplicate code.
Inheritance also enables developers to create a hierarchy of classes, where a child class can inherit the characteristics of a parent class and add new features or override existing ones. This helps to promote a more organized and structured approach to programming.
How to Implement Inheritance in PHP
To implement inheritance in PHP, you need to use the extends keyword. The basic syntax is as follows:
A child class extends a parent class using the extends keyword, like this: class Child extends Parent. The child class inherits all the properties and methods of the parent class and can also add new properties and methods or override the ones inherited from the parent class.
Here’s an example of inheritance in PHP:
class Vehicle {
public $color;
function __construct($color) {
$this->color = $color;
}
function displayColor() {
echo $this->color;
}
}
class Car extends Vehicle {
public $model;
function __construct($color, $model) {
parent::__construct($color);
$this->model = $model;
}
function displayInfo() {
$this->displayColor();
echo " " . $this->model;
}
}
In this example, the Car class extends the Vehicle class, inheriting its properties and methods. The Car class also adds a new property $model and a new method displayInfo().
1 thought on “What is Inheritance in PHP?”