Introduction to PHP - Object Oriented Programming Part 4

Guest Posts Paolo Nikko Nuñal

Another advantage of using OOP is the fact that you can inherent classes. This means that whatever methods and properties that another class posses you can easily "inherit" all of it without you having to repeatedly create another method or property that have the same functionality.

In this example we are going to extend to the Person class. As we all know, that there are many types of Persons, there are employers, students, politicians and the lists goes on and on. For our example we are going to create an Employee class.

<?php
   class Employee
   {
       private $salary;
       private $employee_type;
   }
?>


From the above example we have created the Employee class with two properties named $salary that accepts the salary of the employee and the $employee_type that accepts what type of employee.

The next thing we are going to do is to add the corresponding getters and setters.

<?php
   class Employee
   {
       private $salary;
       private $employee_type;

       public setSalary($salary)
       { 
            $this->salary = $salary;
       }
        public getSalary()
       {
            return $this->salary; 
       }
        public setSalary($employee_type)
       { 
            $this->employee_type = $employee_type;
       }
       public getSalary()
       { 
            return $this->employee_type;
       }
   }
?>


Finally, add the keyword "extends" to extend to the class Person.

 class Employee extends Person


From the code above, we have extended the Employee class to the Person class, which means we can use all of the methods and properties that is being declared or used in the Person class. However, we need to create a constructor first to fully able to use the inherited properties. Continue to our next tutorial to learn more about it.