Thursday 13 May 2021

Php: Override method definitions in subclass

You can override the properties, methods defined in super class by redefining them in subclasses.

 

overriding_demo.php

#!/usr/bin/php

<?php

   class Employee{
        var $id;
        var $first_name;
        var $last_name;
        var $country='India';
        var $designation = 'Developer';

        function about_me(){
            echo "Hello ($this->first_name,$this->last_name), you are from $this->country\n";
        }
   }

   class Manager extends Employee{
       var $reportee_ids;
       var $designation = 'Engineering Manager';

       function about_me(){
           echo "first_name : $this->first_name\n";
           echo "last_name : $this->last_name\n";
           echo "designation : $this->designation\n";
           echo "Reportee ids : ";
           print_r($this->reportee_ids);
       }
   }

   $manager1 = new Manager();
   $manager1->id = 1;
   $manager1->first_name = 'Vadiraj';
   $manager1->last_name = 'Arora';
   $manager1->reportee_ids = array(2, 3, 43, 21);

   $manager1->about_me();

   echo $info;
?>

 

Output

$./overriding_demo.php 

first_name : Vadiraj
last_name : Arora
designation : Engineering Manager
Reportee ids : Array
(
    [0] => 2
    [1] => 3
    [2] => 43
    [3] => 21
)

 

As you see the definition of Manager class,

a.   Property $designation is redefined (overridden)

b.   Method about_me is redefined (Overridden).

 


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment