hierarchical inheritance refers to a situation where multiple classes inherit from a common base or parent class. 

// Base class
class Animal {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function eat() {
        echo "{$this->name} is eating.";
    }
}

// First subclass
class Mammal extends Animal {
    public function sleep() {
        echo "{$this->name} is sleeping.";
    }
}

// Second subclass
class Dog extends Mammal {
    public function bark() {
        echo "{$this->name} is barking.";
    }
}

// Creating instances of the subclasses
$dog = new Dog('Buddy');

// Accessing methods from the base and subclasses
$dog->eat();    // Inherited from Animal
$dog->sleep();  // Inherited from Mammal
$dog->bark();   // Specific to Dog

In this example:

  • The Animal class is the base class with a constructor that sets the name and an eat method.
  • The Mammal class extends Animal and adds a sleep method.
  • The Dog class extends Mammal and adds a bark method.
    Instances of the Dog class can access methods from all three classes in the hierarchy. The eat method is inherited from Animal, the sleep method is inherited from Mammal, and the bark method is specific to the Dog class. This is an example of a simple hierarchical inheritance structure.