Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class, called the parent or base class. In PHP, inheritance is achieved using the “extends” keyword.
When a class extends another class, it inherits all of its public and protected properties and methods, and can override or extend them as needed. This allows for code reuse and reduces duplication, since common functionality can be defined in the parent class and reused in the child classes.
Here’s an example of inheritance in PHP:
class Vehicle {
protected $speed;
public function __construct($speed) {
$this->speed = $speed;
}
public function move() {
echo "Moving at speed " . $this->speed . "\n"; }
}
class Car extends Vehicle {
private $color;
public function __construct($speed, $color) {
parent::__construct($speed);
$this->color = $color;
}
public function getInfo() {
echo "This car is " . $this->color . " and is moving at speed " . $this->speed . "\n"; }
}
$car = new Car(50, 'red');
$car->getInfo(); // Output: This car is red and is moving at speed 50
In this example, the “Vehicle” class defines a common property and method for all vehicles, while the “Car” class extends the “Vehicle” class and adds a new private property “color” and a new public method “getInfo”. The “Car” class also overrides the constructor of the “Vehicle” class to include the “color” property.
By inheriting from the “Vehicle” class, the “Car” class has access to the “speed” property and the “move” method, and can override or extend them as needed. This allows for code reuse and reduces duplication, since the common functionality is defined in the parent class and reused in the child classes.