Google News
logo
PHP program to demonstrate the multi-level inheritance
In the following example of PHP program to demonstrate multi-level inheritance :
Program :
<?php
class Person {
    private $name;
    private $age;

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

    public function getName() {
        return $this->name;
    }

    public function getAge() {
        return $this->age;
    }
}

class Employee extends Person {
    private $employeeId;

    public function __construct($name, $age, $employeeId) {
        parent::__construct($name, $age);
        $this->employeeId = $employeeId;
    }

    public function getEmployeeId() {
        return $this->employeeId;
    }
}

class Manager extends Employee {
    private $department;

    public function __construct($name, $age, $employeeId, $department) {
        parent::__construct($name, $age, $employeeId);
        $this->department = $department;
    }

    public function getDepartment() {
        return $this->department;
    }
}

// Create an instance of Manager
$manager = new Manager('John Doe', 35, 'EMP001', 'Sales');

// Access methods from Person class
echo $manager->getName() . '<br>';
echo $manager->getAge() . '<br>';

// Access methods from Employee class
echo $manager->getEmployeeId() . '<br>';

// Access methods from Manager class
echo $manager->getDepartment() . '<br>';
?>
Output :
John Doe
35
EMP001
Sales
In this program, we have created three classes - `Person`, `Employee`, and `Manager`. `Employee` class extends `Person` class and `Manager` class extends `Employee` class, which makes `Manager` class the child of `Employee` class, and `Employee` class is the child of `Person` class.

In the `Manager` class, we have added a new property called `department`, which is not present in its parent classes. We have also overridden the constructor of each class to add its own properties.

We have created an instance of the `Manager` class and used its methods to access its own properties as well as the properties of its parent classes.