Types of inheritance in php with example

It is a concept of accessing the features of one class from another class. If we inherit the class features into another class, we can access both class properties. We can extends the features of a class by using 'extends' keyword.

  • It supports the concept of hierarchical classification.
  • Inheritance has three types, single, multiple and multilevel Inheritance.
  • PHP supports only single inheritance, where only one class can be derived from single parent class.
  • We can simulate multiple inheritance by using interfaces.

Example 1

Output:

Example 2

Output:


For Videos Join Our Youtube Channel: Join Now

Feedback

  • Send your Feedback to [email protected]

Help Others, Please Share

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.

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:

  • 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:

 

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:

 

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:

 

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.

The following program illustrates single level inheritance in PHP:

  • 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. 

The following program illustrates multilevel inheritance in PHP:

  • 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.

The following program illustrates hierarchical inheritance in PHP:

 

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:

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:

 

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:

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.

 

  • 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]

With the final keyword. [WIll throw an error, to prevent method overriding].

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.

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: 

  • 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: 

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.
Are you a web developer or interested in building a website? Enroll for the Full Stack Web Developer - MEAN Stack Master's Program. Explore the course preview!

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!

What are the types of inheritance in PHP?

Inheritance has three types, single, multiple and multilevel Inheritance. PHP supports only single inheritance, where only one class can be derived from single parent class. We can simulate multiple inheritance by using interfaces.

What is inheritance in PHP with example?

Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.

What are the types of inheritance with example?

Visibility Modes.

What is multilevel inheritance in PHP?

Multiple Inheritance is the property of the Object Oriented Programming languages in which child class or sub class can inherit the properties of the multiple parent classes or super classes.

Chủ Đề