Multilevel inheritance refers to a situation where a class extends another class, and then a third class extends the second class, forming a chain of inheritance. This creates a hierarchy of classes, where each class inherits properties and methods from its parent class.
Example:
// Base class
class Animal {
public function eat() {
echo "Animal is eating";
}
}
// First level of inheritance
class Mammal extends Animal {
public function breathe() {
echo "Mammal is breathing";
}
}
// Second level of inheritance
class Cat extends Mammal {
public function meow() {
echo "Cat says meow";
}
}
// Creating an instance of the Cat class
$myCat = new Cat();
// Accessing methods from different levels of inheritance
$myCat->eat(); // Inherited from Animal
$myCat->breathe(); // Inherited from Mammal
$myCat->meow(); // Defined in Cat class
In this example, Cat is a subclass of Mammal, which is itself a subclass of Animal. As a result, Cat inherits both the eat() method from Animal and the breathe() method from Mammal, in addition to having its own method meow().