Inheritance in PHP

Inheritance in PHP is a way to reuse once written code again and again. The class which is inherited is called base calls and  the class which inherits is called derived class. So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base class, hence making code reusable.

Types of Inheritance

We have  different types of Inheritance. Namely,

  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance

lets take an example of Inheritance


<?php

class friends   ///////////creating a class friends
{
 public $name;  ////////////// declare public variable

 public function Greet()  ////////////// declare public Function
 {
 return "Hello, my name is " . $this->name;
 }
}

?>
 

 

//now create a new class which inherits to class friends
<?php
class girl extends friends
{
    
}
?>
////now create a object of Class girl and call Greet() of class friend
<?php
$grl= new girl();
echo $grl->Greet() ;  // it will give output from friends class 
?>

One thought on “Inheritance in PHP

Leave a Reply