What is Inheritance?

Inheritance is one of the four pillars of Object-Oriented Programming (OOPs). Inheritance is the phenomenon by which a child class can inherit all the properties and characteristics of the parent class. 

You can understand this with a simple real-life example. Consider the example of human beings. You inherit characteristic features from the class ‘Humans’, such as walking, sitting, running, eating, etc. The class ‘Humans’ inherits from the class ‘Mammal’, these characteristic features - making the class ‘Human' a derived class of ‘Mammal’. Furthermore, the class ‘Mammal’ gets its characteristic features from another yet another class - ‘Animal’. This makes the class ’Mammal’ a derived class of the ‘Animal’ class; also making the ‘Animal’ class  a base class.

Inheritance in PHP

Inheritance in PHP is an important OOPs concept and can not be overlooked. Understanding inheritance in PHP is necessary to get a holistic view of object-oriented concepts in PHP.

Inheritance provides you with many benefits that make PHP programming a lot more convenient. One such benefit is code reusability. Reusability allows you to generate clean code and the replication of code gets reduced to almost zero. Reusing existing codes serves various advantages. It saves time, cost, effort, and increases a program’s reliability. Moreover, the program becomes intuitive.

PHP offers mainly three types of inheritance based on their functionality. These three types are as follows:

  • Single Inheritance: Single inheritance is the most basic or fundamental type of inheritance offered by PHP. There is only one base class and one sub/derived class in a single inheritance and the subclass is directly inherited from the base class.
  • Hierarchical Inheritance: As the name suggests, the hierarchical inheritance adopts a tree-like structure, where multiple derived classes are inherited from the base class.
  • Multilevel Inheritance: Multilevel inheritance is the third type of inheritance supported in PHP. It occurs at different levels. Here, one base class is inherited by a derived class, then that derived class is inherited by other derived classes, and so on.

This article will discuss all these types in detail, later.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The Syntax for Inheriting a Class in PHP

Depicted below is the syntax that is used to extend a base class in PHP.

class derived_class_name extends base_class_name {

    // define member functions of

    // the derived class here.

}

The keyword extends is used to define a derived or child class in PHP.

  • derived_class_name: It specifies the name of the derived or the child class. The child class, also known as a subclass, inherits its salient features or characteristics from its parent class. There can be one or over one derived class that inherits from the same base class depending on what type of inheritance is performed. There are three visibility modes supported in PHP: Public, Private, and Protected, which specify how the derived class will inherit what.

  • base_class_name: It specifies the name of the base or the parent class from which the child class is inheriting its properties. A base class is also known as a parent class because all the classes that are termed as derived classes or child classes inherit their properties from the base class. There can be one or more base classes in a program, depending upon the type of inheritance. For instance, in a single-level inheritance, there will be one base class for one child class, but in a multilevel inheritance, one child class can inherit from over one base class in more than one level.

Access Modifiers in PHP

The access modifier (private, public, or protected) used in the definition of the member functions and data members of the derived class specifies the mode with which the features of the base class are derived. The access modifier controls where and how the data members and member functions of a base class can be inherited by the child classes. These access modifiers are used to restrict the access of the base class from the child class to encapsulate the data. This is popularly known as data hiding.  

In PHP, there are three access modifiers: 

  • Public:

Public access modifier gives the least privacy to the attributes of the base class. If the access modifier is public, it means that the derived class can access the public and protected members of the base class but not the private members of the base class. 

The following example shows a class with public members:

class derived_class_name extends base_class_name

{

  // public data member

  public $var_name;    

  // public member function

  public function function_name()

  {

    // define the function here

  }

 } 

The following program illustrates the public access modifier in PHP:

<?php

 // Define the base class

class Jewellery {

    public $price = "We have a fixed price of 100000";

    function printMessage() {

        echo $this->price;

        echo PHP_EOL;

    }

}

 //  define the derived classes

class Necklace extends Jewellery {

    function print(){

        echo $this->price;

        echo PHP_EOL;

    }

}

// create the object of the

// derived class.

$obj= new Necklace;

 // call the functions

echo $obj->price;

echo PHP_EOL;

 $obj->printMessage();

 $obj->print();

?>

InheritanceInPHP_1

  • Private:

Private access modifier provides the maximum privacy to the attributes of a base class. You can access a privately declared data member or member function only within the class in which they are declared.

The following example demonstrates a class with private members: 

class derived_class_name extends base_class_name

{

  // private data member

  private $var_name;    

 // private member function

  private function function_name()

  {

    // define the function here

  }

}

Although the direct accessibility of a private member is not possible, you can access them indirectly using public member functions in the class. If the private members are accessed by a public member in a class, then any child class accessing this public function can also access that private member.

The following program illustrates the private access modifier in PHP:

<?php

// Define the base class

class Jewellery {

    private $price = "We have a fixed price of 100000";

    private function show()

    {

        echo "This is a private method of a base class";

    }

}

//  define the derived classes

class Necklace extends Jewellery {

    function printPrice()

    {

        echo $this->price;

    }

}

// create the object of the

// derived class

$obj= new Necklace;

// this line is trying to 

// call a private method.

// this will throw error

$obj->show();

// this will also throw error

$obj->printPrice();

?>

InheritanceInPHP_2. 

In this program, you’re trying to access a private member directly in a derived class. That’s why it’s throwing an error.

  • Protected:

Protected access modifier provides an intermediate privacy level to the members of a class. If the access specifier is protected, this means that the derived class can access the public and protected members of the base class. The protected members of a base class can be accessed within that class and by its child classes.

The following example demonstrates a class with protected members: 

class derived_class_name extends base_class_name

{

  // protected data member

  protected $var_name;    

 // protected member function

  protected function function_name()

  {

    // define the function here

  }

}

The following program illustrates the protected access modifier in PHP:

<?php

// Define the base class

class Jewellery {

    protected $price1 = 10000;

    protected $price2 = 20000;           

    // Subtraction Function

    function total()

    {

        echo $sum = $this->price1 + $this->price2;

        echo PHP_EOL;

    }   

}

 

// define the derived classes 

class Necklace extends Jewellery {

    function printInvoice() 

    {

        $tax = 100;

        echo $sub = $this->price1 + $this->price2 + $tax;

        echo PHP_EOL;

    }

}

$obj= new Necklace;

$obj->total();

$obj->printInvoice();

?>

InheritanceInPHP_3 

Child Class With Its Own Methods and Properties

In inheritance, the purpose of inheriting the properties and members of a base class by a child class is well achieved. When a child class inherits from a base class, it has direct access to all the non-private members of the base class. And even the private members can be accessed indirectly. 

However, a child class can also have its own methods and properties. Apart from the members of the base class, a derived class can have as many data members and methods as you want. A derived class is just like any other class, with the benefit of having access to some other methods and properties of a base class. This is what inheritance is all about.  

The following program illustrates a child class having access to the properties of its base class along with its methods and properties:

<?php

// Define the base class

class base_class {

    // data member of the base class

    public $data_mem = 10;

    // member function of the base class

    public function member_func()

    {

        echo "I am the base class function.";

        echo "I am the base class data member: ";

        echo $this->data_mem;

    }

}

//  define the derived classes

class child_class extends base_class {    

    // member function of the child class

    function child_func()

    {   echo "I am the child class function.";

        echo $this->data_mem;

    }

}

// create the object of the

// derived class

$obj= new child_class; 

// call method of the base class

$obj->member_func();

// call method of the child class

$obj->child_func();

?>

InheritanceInPHP_4 

Types of Inheritance in PHP

The following three types of inheritance are supported in PHP.

  • Single Inheritance

Single inheritance is the most basic and simple inheritance type. As the name suggests, in a single inheritance, there is only one base class and one sub or derived class. It directly inherits the subclass from the base class.

InheritanceInPHP_Flowchart_1

The following program illustrates single level inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

   var $cost = 10000;

    public function printName($name) {

        echo 'This is base class: Jewellery & name of jewellery is: ' . $name . PHP_EOL; 

    } 

}

// derived class named "Necklace"

class Necklace extends Jewellery {

    public function printName($name) {

        echo 'This is child class: Necklace & name of jewellery is: ' . $name . PHP_EOL;

       // this class can access 

        // data member of its parent class.

        echo 'Price is: ' . $this->cost . PHP_EOL;

    }

}

$f = new Jewellery();

$s = new Necklace();

 $f->printName('Ring'); 

$s->printName('Necklace'); 

 ?>

InheritanceInPHP_5.

  • Multilevel Inheritance

Multilevel Inheritance is another type of inheritance that is found in PHP. Multilevel inheritance can also be explained by a family tree. There is one base class. This base class can be inherited by. These subclasses (not every subclass necessarily) act as base class and are further inherited by other subclasses. This is just like a family having descendants over generations. 

InheritanceInPHP_Flowchart_2

The following program illustrates multilevel inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

    public function totalCost() {

        return  ' total jewellery cost: 600000';

    }  

}

// derived class named "Necklace"

// inherited form class "Jewellery"

class Necklace extends Jewellery {

    public function necklace() {

        return  ' necklace cost: 450000';

    }

}

// derived class named "Pendant"

// inherited form class "Necklace"

class Pendant extends Necklace {

    public function pendantCost() {

        return  ' pendant cost: 600000';

    }

       public function priceList() {

        echo '1. ' .$this->totalCost() . PHP_EOL;

        echo '2. ' .$this->necklace() . PHP_EOL;

        echo '3. ' .$this->pendantCost() . PHP_EOL;

    }

// creating object of 

// the derived class

$obj = new Pendant();

$obj->priceList();

?>

InheritanceInPHP_6

  • Hierarchical Inheritance

As the name suggests, hierarchical inheritance shows a tree-like structure. Many derived classes are directly inherited from a base class. In this type of inheritance, more than one derived class shares the same parent class.

InheritanceInPHP_Flowchart_3

The following program illustrates hierarchical inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

    public function Jewellery() {

        echo 'This class is Jewellery ' . PHP_EOL; 

    } 

}

// derived class named "Necklace"

class Necklace extends Jewellery {  

}

// derived class named "Necklace"

class Bracelet extends Jewellery {  

}

// creating objects of 

// derived classes

// "Necklace" and "Bracelet"

$n = new Necklace();

$b = new Bracelet(); 

?>

InheritanceInPHP_7. 

Protected Access Modifier in PHP

As discussed earlier, protected members of a class can only be accessed within that class and by the derived classes that inherit it. Even an instance of the derived class cannot access the protected member of its base class, outside of that class. This means that the protected members can be accessed only by a derived class and the base class itself, and not anywhere else in the program. 

The following programs illustrate the accessibility of protected members in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

    public $cost = 10000;

    // protected member function 

    // of the base class

    protected function display() {

        echo 'This is the base class.' . PHP_EOL; 

    } 

}

// derived class named "Necklace"

class Necklace extends Jewellery {

    public function show() {

        echo 'This is the child class. ' . PHP_EOL;

    } 

}

// create an object of the derived class

$obj = new Necklace();

// call function of derived class 

$obj->show(); 

// call "protected" function of base class

$obj->display();        // this will throw error

?>

InheritanceInPHP_8

In the above program, an instance of the derived class tries to call a protected member function of its base class outside both of the classes. That’s why the program is throwing an error.

This issue can be solved using a public method. Since a protected member can be directly accessed inside the derived class, so calling the protected member in a public method of the derived class makes it possible to achieve the task of accessing the protected member indirectly.

The following program illustrates this:

<?php

// base class named "Jewellery"

class Jewellery {

    public $cost = 10000;

    // protected member function 

    // of the base class

    protected function display() {

        echo 'This is the base class.' . PHP_EOL; 

    } 

}

// derived class named "Necklace"

class Necklace extends Jewellery {

    public function show() {

        echo 'This is 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 Necklace(); 

// call function of derived class 

$obj->show(); 

?>

/InheritanceInPHP_9 

Overriding Inherited Methods in PHP

Function overriding is supported by inheritance in PHP. It can be observed when a derived class and base class both contain a function having the same name. Both the functions should have the same number of arguments. The derived class inherits the member functions and data members from its base class. So to override a certain functionality, you perform function overriding. 

The following program illustrates the concept of method overriding in PHP:

<?php

// base class named "base_class"

class base_class {

    // "show" function of the base class 

    public function show() {

        echo 'This is the base class.' . PHP_EOL; 

    } 

}

 // derived class named "derived_class"

class derived_class extends base_class {

    // "show" function of the derived class 

    public function show() {

        echo 'This is the derived class. ' . PHP_EOL;

    }

}

 // create an object of the derived class

$obj = new derived_class();

// will call the "show" 

// function of the derived class

$obj->show();  

?>

InheritanceInPHP_10.

In the program above, both the base class (i.e. base_class) and the derived class (i.e. derived_class) have a function called “show”. If an instance of the derived class calls the show() function, then PHP will call the show() function of the derived call. This is because the derived_class overrides the show() of the base_class with its own show() method. If an instance of the base class uses the show() method, then there will be no overriding of the method.

The Final Keyword in PHP

Final is a critical keyword in OOPs concepts in PHP and is found in various programming languages such as Java, JavaScript, etc. However, the Final keyword serves different purposes in different languages. 

In PHP, the final keyword serves different purposes depending upon whether it’s used with a class or a method.

  • The final keyword used with a class: The final keyword with a class, serves the purpose of preventing inheritance. If a class is declared final, using the keyword “final”, then inheriting that class will cause the program to throw an error. This can be useful in a case when you don’t want a class and its members to be accessed anywhere else in the program. 

The following program illustrates the concept of the “final” keyword with classes in PHP:

Note: This code will throw an error as we are trying to inherit a final class.

<?php

   final class Jewellery {

      final function displayMessage() {

         echo "I am a final class. You can not inherit my properties!";

      }

      function print() {

         echo "I am the Jewellery class function.";

      }

   }

   class testClass extends Jewellery {

      function show() {

         echo "I am the test class function.";

      }

   }

   $obj = new testClass;

   $obj->show();

?>

InheritanceInPHP_11 

  • The final keyword used with a method: The final keyword when used with a method, serves the purpose of preventing method overriding. If a method has been declared final, using the “final” keyword, then another function with the same name and same parameters can not be defined in a derived class. Calling such a function will cause the program to throw an error. 

The following programs illustrate the concept of the “final” keyword with methods in PHP:

Without the final keyword (will produce output, but will cause method overriding)

<?php

   class Jewellery {    

      function printMessage() {

         echo "I am the function of derived class.";

      }

   }

   class testClass extends Jewellery {      

      function printMessage() {

         echo "I am the function of derived class.";

      }

   }  

   $ob = new testClass;

   $ob->printMessage();

?>

InheritanceInPHP_12

With the final keyword. (WIll throw an error, to prevent method overriding).

<?php

   class Jewellery {    

      final function printMessage() {

         echo "I am the function of derived class.";

      }

   }

   class testClass extends Jewellery {

            function printMessage() {

         echo "I am the function of derived class.";

      }

   }

   

   $ob = new testClass;

   $ob->printMessage();

?>

InheritanceInPHP_13

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Multiple Inheritance in PHP Using Traits or Interfaces

Multiple inheritance is a type of inheritance in which one class can inherit the properties from more than one parent class. In this type of inheritance, there is one derived class, that is derived from multiple base classes. This is one of the most important and useful concepts provided in the object-oriented paradigm and serves the purpose wherein you want one class to inherit different types of properties (which are in different classes). 

For example, consider a class called parrot. Now, since a parrot is a bird, and it can also be a pet or simply a living creature, so, the class parrot can serve different properties. So,  using multiple inheritance, the parrot class can inherit the properties of all three classes bird, pet, and living_creature.

InheritanceInPHP_Flowchart_4.

Many programming languages do not support multiple inheritance directly like Java and PHP. However, PHP provides some ways to implement multiple inheritance in your programs. In the PHP programming language, multiple inheritance is achieved by using two ways:

  • Traits:

Traits are used to reduce the complexity of a program by writing consistent functionalities that can be used by other classes in the program. A trait is like a class, it can have functions as well as abstract methods. The functionalities defined in a trait can be accessed by other classes in the PHP program. 

The traits can be used to implement the concept of multiple inheritance in PHP. 

Syntax

class derived_class_name extends base_class_name {

    use trait_name;   // “use” keyword to use a trait

    ...

    ...

    // base_class functions

}

The following program illustrates the usage of traits to implement multiple inheritance: 

<?php

// declare a class

class Bird {

    public function display() {

        echo "I am a bird,";

    }

}

// declare a trait

trait Pet {

    public function show() {

        echo " a pet";

    }

}

// declare a derived class

class Parrot extends Bird {

    // keyword "use" to use the trait

    use Pet;

    public function msg() {

        echo ", and a parrot.";

    }

// declare object of the derived class

$test = new Parrot();

$test->display();

$test->show();

$test->msg();

?>

InheritanceInPHP_14

  • Interfaces:

Interfaces are used when there are objects that share the same functionality, but you don’t want the objects to know about each other. In other words, an interface provides contracts for the objects, without knowing anything else about one another.

Interfaces can also be used to implement multiple inheritance in PHP.

Syntax

// use the keyword "implement"

// to use interface

class derived_class extends base_class implements interface_name

The following program illustrates the usage of interfaces to implement multiple inheritance: 

<?php

// define a class

class Bird {

     public function insideBird() {

          echo "I am bird, ";

     }

}

// declare an interface

interface Pet {

     public function insidePet();

}

 // define a derived class

// inherited from Bird class

// and implementing Pet interface

class Parrot extends Bird implements Pet {

     function insidePet() {

          echo "and a pet, ";

     }

     public function insideParrot() {

     echo "and a parrot.";

     }

}

// create object of the derived class

$obj = new Parrot();

$obj->insideBird();

$obj->insidePet();

$obj->insideParrot();

?>

InheritanceInPHP_15

Importance of Inheritance in PHP

Inheritance in itself is one of the most important concepts introduced in object-oriented programming. Following are some of the key points highlighting the importance of inheritance in PHP:

  • Code reusability: Inheritance strongly supports code reusability. Since the functionalities and properties of one class can be inherited and used by other classes, there is no need to write those functionalities repeatedly in different sections of the program.
  • Data hiding: Data hiding is one of the most important aspects of inheritance. Accessibility of the data can be easily controlled by using the access modifiers, and only the required data is allowed to access outside the class.
  • Extensibility: Inheritance provides a way to write extensible programs. This means that the required functionalities or classes can be extended when there is a requirement in the future growth of the program or application. 
  • Overriding: The concept of method overriding can be easily achieved in PHP. The methods of a base class can be redefined in the derived class as per the requirement of the program. Those functions are overridden in the derived class, without causing any errors.
  • Reduced complexity: The complexity of code is also reduced as common properties can be simply inherited, without the need to redeclare them. This makes the code convenient.

Wrapping Up!

In this article, you have learned about inheritance in PHP. You explored PHP and its object-oriented concepts in depth. You dived deep into the uses, types, modes, and all other important concepts of inheritance. This article discussed in detail several other related concepts such as final keyword, method overriding, access modifiers, etc.

To get started with PHP as a beginner, you can refer to this video. Take up our PHP Training online course to learn PHP and build dynamic applications guided by industry experts. If you are a PHP professional, you can enroll in our Advanced PHP Development Training to upskill. This will allow you to learn advanced PHP concepts such as sessions, cookies, etc.

Don’t just stop here. To learn MEAN stack development and to give yourself a chance to work for top tech giants, check out our course on Full Stack Web Developer - MEAN Stack. In this course, you will learn some of the hottest skills like Node, Mongo, etc. that will help you to set your foot into professional web development. To get a complete list of free courses offered by Simplilearn, visit Free Courses.

If you have any questions for us, please mention them in the comments section and we will have our experts answer them for you.

Happy Learning!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449