w3resource

PHP class inheritance with extended class


11. Employee Extending Person

Write a class called 'Employee' that extends the 'Person' class and adds properties like 'salary' and 'position'. Implement methods to display employee details.

Sample Solution:

PHP Code :

<?php
 class Person {
    protected $name;
    protected $age;

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

    public function __toString() {
        return "Name: " . $this->name . "\n" .
               "Age: " . $this->age . "\n";
    }
}

class Employee extends Person {
    private $salary;
    private $position;

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

    public function getSalary() {
        return $this->salary;
    }

    public function getPosition() {
        return $this->position;
    }

    public function displayDetails() {
        echo "Name: " . $this->name . "</br>";
        echo "Age: " . $this->age . "</br>";
        echo "Salary: " . $this->salary . "</br>";
        echo "Position: " . $this->position . "</br>";
    }
}

$employee = new Employee("Pratik Octavius", 33, 6000, "Manager");
$employee->displayDetails();

?>

Sample Output:

Name: Pratik Octavius
Age: 33
Salary: 6000
Position: Manager

Flowchart:

Flowchart: PHP class inheritance with extended class.

For more Practice: Solve these Related Problems:

  • Write a PHP class Employee that inherits from Person and adds properties like salary and position, then displays a combined profile.
  • Write a PHP program to create an array of Employee objects and sort them by salary, then output their details.
  • Write a PHP script to override the __toString() method in Employee to include department and bonus information.
  • Write a PHP function to calculate the average salary of a group of Employee objects and output the result.

Go to:


PREV : Person Class with __toString().
NEXT : Product Class with Comparable Interface.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.