Inheritance in PHP
Updated on 26th Dec, 23 9.1K Views

This blog covers the topic of inheritance in PHP. We will discuss the types of inheritance in PHP with examples. Also, you will learn how multiple inheritance is achieved in PHP. Apart from this, you will get to know about why we use the final keyword.  

Table of Contents:

Watch this video course on PHP to learn PHP from the beginning:

Introduction to Inheritance

Inheritance is one of the important pillars of every object-oriented programming language. It involves deriving the properties of one class from another class. This concept helps promote code reusability. Moreover, we can create new classes with shared characteristics. The class that inherits the properties is known as the child, derived, or subclass, and the class from which the properties are being inherited is known as the parent, base, or superclass.

Advance your PHP knowledge with Intellipaat’s comprehensive PHP course.

Inheritance in PHP

The concept of inheritance in PHP is similar to other object-oriented programming languages, such as Java and C++. As in biological inheritance, a child inherits the properties of his parents; in PHP, a class can inherit properties from another class. It is a way to extend the functionality of a base class to the derived class. 

Syntax

For inheriting a class in PHP, we use the keyword “extends,” and the syntax for deriving a class is as follows:

class derived_class_name extends base_class_name {
    // member functions of the derived class.
}

The following example will help you understand the concept in a better manner:

<?php  
class Base 
    {  
        function fun1()  
        {  
            echo "Intellipaat";  
        }  
    }  
    class Derived extends Base  
    {  
        function fun2()  
        {  
            echo "Hello! ";  
        }  
    }  
    $obj= new Derived();  
    $obj->fun2();
    $obj->fun1();  
?>  

In this example, we have created the object of the derived class, through which we are calling the function of Base class as well as Derived class, which means we are inheriting the features of the base class in the derived class. 

The output we receive is as follows:

Hello! Intellipaat 

Access Modifiers in PHP

The access modifiers are used to control where and how the data members and member functions of a base class can be inherited by the derived classes. There are three access modifiers in PHP, i.e., public, private, and protected. In case, we do not mention any access specifier, all classes and their members will be treated as public by default.

Public: The properties of a class that are declared public can be accessed in any other part of the code, be it inside or outside the class. The public properties can also be modified from anywhere in the code. 

The following example illustrates how the public access specifier works in PHP:

<?php
class Fruit {
  public $name;
}
$obj = new Fruit();
$obj->name = 'Mango'; // OK
echo $obj->name ;
?>

Here, the variable ‘name’ is public; therefore, we can access and modify its value from outside the ‘Fruit’ class. The output of this program is:

Mango

Private: These properties are accessible only to the code inside the class. The properties of a private class are accessible only to the objects and member functions of the same class. The following example demonstrates how we can access the private members of a class in PHP:

<?php
class Test {
  private $x = 10;
  public function add() {
    $this->x++;
 }
  public function getNumber() {
    return $this->x;
  }
}
$obj = new Test();
$obj->add();
echo "The number after increment is " . $obj->getNumber();
?>

Here, the variable x is a private variable of the class, and we are accessing this variable through the object of the same class, i.e., Test. 

The output that we get is as follows:

The number after increment is 11

Protected: This mode of access is a bit similar to a private class, i.e., the content of this class cannot be accessed outside the class. The only difference is that the derived class can access the properties of a protected base class. However, we cannot directly access the protected member function outside the class anywhere else in the program, not even through the object of the derived class. We can do it through derived classes. We can derive protected members in the derived class, and through the derived class, we can indirectly access them anywhere in the program. See the following example to understand it better:

<?php
// base class named "Base"
class Base {
    public $x = 50;
    // protected member function of the base class
    protected function display() {
        echo 'Inside the base class.' . PHP_EOL; 
    } 
}
// derived class named "Child"
class Child extends Base {
    public function show() {
        echo 'Inside the child class. ' . PHP_EOL;
        // protected member function of the base class can be accessed in this derived class
        $this->display();
    }

// create an object of the derived class
$obj = new Child(); 
// call function of derived class 
$obj->show(); 
?>

Here, we have derived the protected function of the base class inside the child class. Through the object of the derived class, we are accessing the protected function. 

The output of this program is as follows:  

Inside the child class. 

Inside the base class.

Types of Inheritance in PHP with Examples

Three types of inheritance are allowed in PHP, and those types include single, multilevel, and hierarchical inheritance. However, we have multiple inheritance, which is not achievable directly but through some other means. We will discuss those in the next section. Let’s first explore the three types of inheritance in detail:

Single Inheritance

Single Inheritance

In this type of inheritance, there is only one parent class and one child class. The child class inherits the parent class directly. The following example will help you understand the concept of single inheritance.

<?php
// base class named "Fruit"
class Fruit {
   var $x = 50;
    public function printName($name) {
        echo 'This is base class: name of the fruit is: ' . $name . PHP_EOL; 
    } 
}
// derived class named "Apple"
class Apple extends Fruit {
    public function printName($name) {
        echo 'This is child class: name of the fruit is: ' . $name . PHP_EOL;
       // this class can access data member of its parent class.
        echo 'Price is: ' . $this->x . PHP_EOL;
    }
}
$f = new Fruit();
$s = new Apple();
 $f->printName('Mango'); 
$s->printName('Apple'); 
 ?>

Here, the ‘Apple’ class extends the ‘Fruit’ class. The derived class, i.e., ‘Apple,’ can access and use the variable x of the base class, i.e., ‘Fruit’, inside itself. So when we call the printName() function of the Apple class, it prints the price stored in the variable x, along with other content of this function. This code will generate the following output:

This is base class: name of the fruit is: Mango

This is child class: name of the fruit is: Apple

Price is: 50

Multilevel Inheritance

Multilevel Inheritance

In multilevel inheritance, a child class inherits one parent class and then acts as a parent class for another child class. In other words, the child class further has its child class. It is like a grandparent having a child and a grandchild. The following example illustrates the concept of multilevel inheritance in PHP:

<?php
// base class named "Fruit"
class Fruit{
    public function Price() {
        return  'Total price of fruits: 500 ';
    }  
}
// derived class named "Apple inherited form class "Fruit"
class Apple extends Fruit {
    public function applePrice() {
        return  'Price of Apples per Kg: 250';
    }
}
// derived class named "Mango inherited from class "Apple"
class Mango extends Apple {
    public function mangoPrice() {
        return  'Price of Mangoes per Kg: 250';
    }
       public function priceList() {
        echo '1. ' .$this->Price() . PHP_EOL;
        echo '2. ' .$this->applePrice() . PHP_EOL;
        echo '3. ' .$this->mangoPrice() . PHP_EOL;
    }

// creating object of the derived class
$obj = new Mango();
$obj->priceList();
?>

Here, the Apple class is extending the Fruit class, and the Mango class is inheriting the Apple class. The output of this program is:

1. Total price of fruits: 500 

2. Price of Apples per Kg: 250

3. Price of Mangoes per Kg: 250

Hierarchical Inheritance

Hierarchical Inheritance

In hierarchical inheritance, more than one child class is inherited from the single parent class. The hierarchy forms a tree-like structure, as shown in the image. An example of hierarchical inheritance is given below: 

<?php
// base class named "Fruit"
class Fruit {
    public function fruit() {
        echo 'This is Fruit class ' . PHP_EOL; 
    } 
}
// derived class named "Apple"
class Apple extends Fruit {  
   public function apple() {
  echo 'This is Apple class ' . PHP_EOL;
  echo '' .$this->fruit() . PHP_EOL;
}
}
// derived class named "Mango"
class Mango extends Fruit {
     public function mango() {
  echo 'This is Mango class ' . PHP_EOL;
  echo ''.$this->fruit() . PHP_EOL;
}}
// creating objects of derived classes"Apple" and "Mango"
$a = new Apple();
$a->apple();
$m = new Mango(); 
$m->mango();
?>

In this program, the apple class is inheriting the fruit class, and the mango class is also inheriting the fruit class. 

The output obtained from this program is as follows:

This is Apple class 

This is Fruit class 

This is Mango class 

This is Fruit class 

Apart from these types, multiple inheritance is also there. In multiple inheritance, there can be more than one parent class for a single child class. In other words, we can inherit the properties of multiple classes into a single class. Multiple inheritance is not supported in PHP, but we can achieve this by using interfaces or traits. This is explained in detail in the next section. 

Ace your PHP Interview with our expertly crafted PHP Interview Questions. Start preparing now!

How to Achieve Multiple Inheritance in PHP

There are two ways in which we can implement multiple inheritance in PHP, i.e., by using traits and interfaces. 

1. By Using Traits Along with Classes: A trait in PHP is similar to a class, except that traits contain methods that can be used in multiple classes. This helps in achieving multiple inheritance in PHP. To declare a trait, we use the keyword “trait,” and to use it in the class, we have the keyword “use.”

The syntax for declaring a trait in PHP is as follows:

<?php
trait TraitName {
  // required code
}
?>

To use a trait in a class, the syntax is as follows:

<?php
class MyClass {
  use TraitName;
}
?>

The following code example illustrates how we can implement multiple inheritance in PHP using traits.

<?php
// trait 1
trait t1 { 
public function sayhello() { 
echo "Hello! Welcome to"; 


// trait 2
trait t2 { 
public function sayfor() { 
echo " Intellipaat."; 


class Child { 
use t1; 
use t2; 
public function fun() { 
echo "\nHappy Learning!"; 


$obj = new Child(); 
$obj->sayhello(); 
$obj->sayfor(); 
$obj->fun(); 
?> 

In this code, we have two traits, t1 and t2, containing methods sayhello() and sayfor(), respectively. These methods from both traits t1 and t2 are being inherited by the child class through its object ‘obj’. This results in the following output:

Hello! Welcome to Intellipaat.

Happy Learning! 

2. By using Interfaces along with Classes: An interface contains public methods that the class must implement. Moreover, interfaces only specify the method signature, i.e., the name of the method and argument list, without the actual implementation.

The syntax of an interface in PHP is as follows:

class child_class_name implements interface_name1, interface_name2...

To understand how we use interfaces to implement multiple inheritance in PHP, refer to this example:

<?php 
interface I1 { 
public function insideI1(); 

interface I2 { 
public function insideI2(); 

class Child implements I1, I2 { 
// Function of the interface B 
function insideI2() { 
echo "\nInside interface I2"; 

// Function of the interface C 
function insideI1() { 
echo "\nInside interface I1"; 

public function insideChild() 

echo "\nInside Child class"; 


$obj = new Child(); 
$obj->insideI1(); 
$obj->insideI2(); 
$obj->insideChild(); 
?> 

In this program, we have two interfaces containing function signatures for the functions insideI1() and insideI2(). The child class inherits these functions and provides implementation of these functions. These methods are invoked with the help of the object of the child class, i.e., ‘obj’. 

The output of this program is as follows:

Inside interface I1

Inside interface I2

Inside Child class 

Check out this blog on How to become a PHP developer

The Final Keyword

This keyword is an important part of PHP. It can be used either with classes or with functions, and its functionality also varies depending on whether it is used with a class or a method. When we use the final keyword with a class, it prevents the inheritance of that class by any other class. That means no class can access the properties of that class. This is helpful when we do not want the properties of a class to be accessed anywhere in the program to enhance code security. 

Let’s see an example where we will use the final keyword with a class.

<?php
   final class Fruit{
      final function fruit() {
         echo "Inside final class. You can not access its properties.";
      }
      function print() {
         echo "I am the fruit class function.";
      }
   }
   class test extends Fruit {
      function display() {
         echo "Inside the function of test class.";
      }
   }
   $obj = new test;
   $obj->display();
?>

In this program, the test class is trying to inherit the fruit class, which is declared final. This is not possible, so we will get an error. The output that we get is as follows:

Fatal error: Class test cannot extend final class Fruit in /tmp/XSxCrusReB.php on line 19

Wrapping Up

Instead of writing simple code, the concept of inheritance should be used, as it has many advantages over normal code. But we should also take care of the security of our code while implementing the inheritance concept in PHP. For this purpose, we have access specifiers, which we have already discussed in this blog. It helps reduce the complexity of code, as we do not need to write the same code again and again in our program. 

Join our thriving PHP community today and connect with like-minded developers!

FAQs

Why do we use the final keyword with a method?

When we want to prevent method overriding in PHP, we use the final keyword. This means that when we declare a function as final in PHP, we cannot use that same method in another class. 

Explain method overriding in PHP.

Method overriding in PHP involves creating and defining a method in the base class and using the same method in the child class with different functionality. 

What is the extend keyword used for?

The extend keyword is used to inherit the base class in the derived class. In other words, we can say that we are extending the base class inside the child class and adding extra functionalities to it. 

What type of inheritance is supported in PHP?

PHP supports single, multilevel, and hierarchical inheritance. Although we can implement multiple inheritance as well, it is not possible directly. We use interfaces and traits to achieve multiple inheritance in PHP.

Course Schedule

Name Date Details
Python Course 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 09 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 16 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *

Speak to our course Advisor Now !

Related Articles

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.