PHP class inheritance is a mechanism that allows one class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).
This allows you to reuse code, extend existing functionality, and follow the principle of "Don’t Repeat Yourself (DRY)".
Basics of Inheritance
1. The extends keyword is used in PHP to create inheritance.
2. A child class automatically inherits all the public and protected properties and methods of its parent class.
3. The child class can:
A. Use the inherited methods and properties directly.
B. Override methods from the parent class.
C. Add new methods and properties.
Example 1: Basic Inheritance
Here, the Dog class inherits from the Animal class but overrides the speak() method.
// Parent class
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
echo "$this->name makes a sound.<br>";
}
}
// Child class
class Dog extends Animal {
public function speak() {
echo "$this->name barks! Woof Woof!<br>";
}
}
// Usage
$animal = new Animal("Generic Animal");
$animal->speak(); // Output: Generic Animal makes a sound.
$dog = new Dog("Buddy");
$dog->speak(); // Output: Buddy barks! Woof Woof!
Example 2: Using parent:: to Call Parent Methods
The Car class overrides the start() method but still uses the parent’s method with parent::start().
class Vehicle {
public function start() {
echo "Starting the vehicle...<br>";
}
}
class Car extends Vehicle {
public function start() {
// Call the parent method first
parent::start();
echo "Car engine started!<br>";
}
}
$car = new Car();
$car->start();
// Output:
// Starting the vehicle...
// Car engine started!
Example 3: Multilevel Inheritance
Human inherits from Animal, and Animal inherits from LivingBeing. So, Human has all methods from both parents.
class LivingBeing {
public function breathe() {
echo "Breathing...<br>";
}
}
class Animal extends LivingBeing {
public function eat() {
echo "Eating...<br>";
}
}
class Human extends Animal {
public function speak() {
echo "Speaking...<br>";
}
}
$person = new Human();
$person->breathe(); // From LivingBeing
$person->eat(); // From Animal
$person->speak(); // From Human