Inheritance in PHP

Introduction

An important feature of object oriented programming is its extensive support for code reuse that relieves programmers from the time-consuming and error-prone process of re-implementing software functionality that has already been written and thoroughly tested, often by highly competent programmers.

Inheritance allows us to define a new class by extending an already existing class, in other words creating a new class with all the functionality of an existing class in addition to some more. The new class is called the sub (or child) class of the parent class. With the use of  the "extend" keyword with the sub class, for inheriting the feature of the super class, in other words the parent class. To specify the difference between the old (parent) class and the new (sub) class. This is done by:

  • Adding new class members (properties and functions) to the derived class, that will consist of the new members plus the members inherited from the old class.
     
  • Modify, if needed, how some of the inherited function array s and properties behave in the derived class by providing a new implementation for those function members.

Consider the following class. The sample code has two classes with the name of "Parent" and "Child". The parent class contains two simple functions with the name of FirstName() and LastName($parameter) and a constructor or say a magic method. In the parent class the FisrtName() function displays the first name of the parent, and the LastName($arguments) function accepts an argument to display the last name of the parent plus child. The child class also contains a FisrtName() function the same as the parent class to display the first name of the child. And to displaying the last name of the child, we do not declare the Lastname() function in the child class, here we used the parent class LastName() function to also display the last name of the child class because the child class extends the Parent class and it inherits all the properties of its Parent class.

<?php

class Parent

{

function __construct()

{

echo "<b>Paraent Class Constructor</b>"."</br>";

}

public function FirstName()

{

echo " The Father name is Pramod ";

}

public function LastName($string)

{

echo $string."</br>";

}

}

class Child extends Parent

{

function __construct()

{

echo "<b>Child Class Constructor</b>"."</br>";

}

public function FirstName()

{

echo "The child name is Himanshu ";

}

}

//parent class object

$baseobj=new Parent();

//calling parent class function

$baseobj->FirstName();

$baseobj->LastName("Dubey");

 //child class object

$childobj=new Child();

//calling child class function with parant class by the help of child class object.

$childobj->FirstName();

$childobj->LastName("Dubey."); //the function that is define in parant class and also used by the child class.

?>

Output

inheritance-in-php.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all