Google News
logo
PHP program to demonstrate the hierarchical or tree inheritance
Hierarchical or tree inheritance is a type of inheritance in which a parent class has multiple child classes, and those child classes can themselves have their own child classes. Here's a PHP program to demonstrate hierarchical inheritance :
Program :
<?php
class Animal {
    protected $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    public function eat() {
        echo "{$this->name} is eating.\n";
    }
}

class Mammal extends Animal {
    public function breathe() {
        echo "{$this->name} is breathing.\n";
    }
}

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

class Cat extends Mammal {
    public function meow() {
        echo "{$this->name} is meowing.\n";
    }
}

// create objects of the classes
$dog = new Dog("Buddy");
$cat = new Cat("Smokey");

// call the methods
$dog->breathe(); // Buddy is breathing.
$dog->eat(); // Buddy is eating.
$dog->bark(); // Buddy is barking.

$cat->breathe(); // Smokey is breathing.
$cat->eat(); // Smokey is eating.
$cat->meow(); // Smokey is meowing.
?>
Output :
Buddy is breathing.
Buddy is eating.
Buddy is barking.
Smokey is breathing.
Smokey is eating.
Smokey is meowing.
In this example, we have an `Animal` class that has a child class `Mammal`, which in turn has two child classes `Dog` and `Cat`. The `Dog` and `Cat` classes inherit properties and methods from their parent classes, and they also have their own unique methods.