Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Multiple Inheritance allowed at class level in PHP?

Is Multiple Inheritance allowed at class level in PHP?

like image 742
OM The Eternity Avatar asked Apr 22 '10 12:04

OM The Eternity


People also ask

Why multiple inheritance is not allowed in PHP?

PHP programming language doesn't even support the multiple inheritance/inheritances. PHP supports multiple inheritances only by using interfaces or Traits in PHP instead of classes so that we can implement it. Traits are a type of class that enables multiple case classes, objects, classes, and traits.

Does multiple inheritance apply to classes?

Multiple inheritance is not supported by Java using classes, handling the complexity that causes due to multiple inheritances is very complex.

What is multiple inheritance in PHP?

What is Multiple Inheritance? Multiple inheritances are one of the four pillars of OOP object-oriented programming, consisting of a child class or a subclass inheriting the traits from multiple parent classes or superclasses.

Why multiple inheritance is not possible using class?

Java doesn't support multiple inheritances in classes because it can lead to diamond problem and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritances.


1 Answers

Multiple inheritance suffers from the Diamond Problem, which has not been (agreed upon how to be) solved in PHP yet. Thus, there is no multiple inheritance in PHP.

    BaseClass
       /\
      /  \
 ClassA  ClassB
      \  /
       \/
     ClassC

If both ClassA and ClassB defined their own method foo(), which one would you call in ClassC?

You are encouraged to either use object composition or interfaces (which do allow multiple inheritance) or - if you are after horizontal reuse - look into the Decorator or Strategy pattern until we have Traits (or Grafts or whatever they will be called then).

Some Reference:

  • [PHP-DEV] Traits,Grafts, horizontal reuse
  • [PHP-DEV] Multiple class inheritance
  • RFC: Traits for PHP
  • Traits-like Functionality in PHP now
like image 83
Gordon Avatar answered Sep 20 '22 23:09

Gordon