Introduction to PHP - Object Oriented Programming Part 5

Guest Posts Paolo Nikko Nuñal

In our previous tutorial we managed to create a new Employee class. We are going to continue with the Employee class and learn how you can create a new "Employee" object and how to use all of the methods and properties in the Person class.

The first thing we are going to do is to create a constructor in the Employee class.

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

       public __construct($name,$age,$gender,$salary,$employee_type)
       {
            parent::__construct($name,$age,$gender);
            $this->salary = $salary;
            $this->employee_type = $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;
       }
   }
?>



From the code above, we have created a constructor.

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




So the constructor in the Employee class accepts 5 parameters namely the $name,$age,$salary and $employeetype. After which you see a keyword "parent". This means that we are calling the parent constructor class of Employee which is Person and that accepts three parameters the $name,$age and $gender.

After which we added the $salary and $employee
type. As you can see, we didn't have to create another getters and setters for the $name,$age and $gender as we merely extends the Employee class to its parent class which is the Person class.

To create a new employee all you have to do is supply the constructor with the required parameters.

       $e1 = new Employee("John Doe",24,"United States",24000,"REGULAR");
       $e1->getSalary();
       $e1->getName();
       $e1->getAge();




That's it, you have created an object $e1 which is an employee and passed the value to its constructor that accepts 5 variables.