Thursday 13 May 2021

Php: Class inheritance

Inheritance is a feature where one class reuse the methods, properties defined in other class.

 

How can I inherit the properties and behaviours from a class?

Using extends keyword, you can specify from which class you want to inherit the properties, methods.

 

Syntax

class Parent{
  
}

class Child extends Parent{
  
}

In the above example, Child class inherit the properties, methods from Parent class. Any object of child class can use the properties, methods defined in Parent class. Let’s see the same with below example.

 

inheritance_demo.php

#!/usr/bin/php

<?php

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

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

   class Manager extends Employee{
       var $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

$./inheritance_demo.php 

Hello (Vadiraj,Arora), you are from India

 

 



 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment