Things you’re going to learn :
- Multiple inheritance problem
- Example of coffee making multiple inheritance example
PHP is a single inheritance language and does not support multiple inheritance which means that you can only extend a single class but there are ways you can achieve something similar to multiple inheritance in PHP using traits or interfaces .
Let's see what the problem is with the multiple inheritance and why we would care to have an alternative to multiple inheritance in PHP. For instance, we have a coffee maker class that has a method called make Multiple inheritance problem coffee and then also let's say that we get the specialty coffee makers like latte maker and cappuccino maker the thing is these specialty coffee makers can also make regular coffee.
In this case we would leverage the power of inheritance and extend the coffee maker from the latte and cappuccino maker and just add additional methods called make latte and make cappuccino. This is single inheritance and it is well supported and works in PHP.
Now let's say that down the road we got an all-in-one coffee maker which can make regular coffee but it can also make latte and you can make cappuccino in addition to some other additional features in some other languages you could use multiple inheritance and simply extend both latin maker and cappuccino maker in the all-in-one coffee maker class this is not supported in PHP and multiple inheritance does have its own problems. One such problem is called the diamond problem.
As you notice this forms a shape of a diamond right the problem is that if we override the make coffee method within both latte and cappuccino maker classes and we do not override the make coffee method within the all-in-one coffee maker.
The all-in-one coffee maker class would not know which make coffee method to run. This is a problem and some programming languages that support multiple inheritance solve this problem in different ways, however , PHP supports traits that lets you share common functionality from multiple classes.