PHP Tutorial

PHP Examples

PHP Practice

PHP program to demonstrate the hierarchical or tree inheritance

Here, we are going to demonstrate the hierarchical or tree inheritance in PHP.
By Nidhi Last updated : December 19, 2023

Hierarchical or Tree Inheritance Example

Here, we will implement hierarchical or tree inheritance. In the hierarchical inheritance, we will inherit the one base class into multiple derived classes.

PHP code to implement hierarchical or tree inheritance

The source code to demonstrate the hierarchical inheritance is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the hierarchical inheritance.
class Base
{
    function BaseFun()
    {
        echo "BaseFun() called<br>";
    }
}

class Derived1 extends Base
{
    function Derived1Fun()
    {
        echo "Derived1Fun() called<br>";
    }
}

class Derived2 extends Base
{
    function Derived2Fun()
    {
        echo "Derived2Fun() called<br>";
    }
}

$Obj1 = new Derived1();
$Obj2 = new Derived2();

$Obj1->BaseFun();
$Obj1->Derived1Fun();

echo "<br>";

$Obj2->BaseFun();
$Obj2->Derived2Fun();

?>

Output

BaseFun() called
Derived1Fun() called

BaseFun() called
Derived2Fun() called

Explanation

In the above program, we created three classes Base, Derived1, and Derived2. Here, we inherited the Base class into both Derived1, Derived2 classes.

At last, we created the objects of Derived1 and Derived2 class and called the methods that will print the appropriate messages on the webpage.

In the above example, we have used the following PHP topics:

PHP Class & Object Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.