Multiple-Inheritance in PHP

Multiple-Inheritance in PHP

Multiple-Inheritance is the resources of the Object Oriented Programming Languages in which child class or subclass can inherit the resources of the multiple parent classes or superclasses.

Multiple inheritance in PHP

PHP does not support Multiple Inheritance but using interfaces in PHP, we can implement it.

Using class with Traits:

The trait is a type of class that enables multiple inheritance. Classes, objects, and traits that do not extend more than one class, but it can extend multiple traits at the same time.

Syntax:

Example:

Output:

  • In the above example, “traits” is used with parent class. There is “class” named “Inheritance” which contains function example() and “trait” named “formultiple” that contains function “examplem()” and a child class named “Sample” and we are creating the object of this class named “check” and we are invoking all the functions of a class and a trait.

Using Multiple Traits:

Multiple Traits can be added into a class by listing them in the use statement, which is separated by commas.

Syntax:

Example:

Output:

  • In the above example, the “traits” have been used. There are two traits named “Multiple” that contain function example() and “multiple” that include function exam(), and there is a child class “Test” and we are creating the object of that class named “check” and we are invoking all the functions of traits.

Using Class along with Interface

Syntax:

Example:

Output:

  • In the above example, Interface “B” used with the class “A” to implement multiple inheritances. The important point is that it cannot define the function inside the interface; it should be set inside the child class “Multiple”. We are calling all the functions using the child (Multiple) objects named “check”.

Multiple Interface

Example:

Output:

In the above example, multiple interfaces have been used to implement multiple inheritances. There are two interfaces called “B” and “C” that are base classes with the child class that is called “Multiple” and we are calling the functions using its object “test”.