Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Why isn't it possible to extend more than one class?

Tags:

oop

php

class

I've faced a situation when I want to extend two parent classes, but php does not allow this.
Why I can't extend more than one class, but can implement more than one interface. What's wrong with extending many classes?
It seemed to me like a pretty obvious thing, until I got parse errors.
Is it a bad practice? If so, what are the alternatives?
Is it possible in other languages?

like image 703
foreline Avatar asked Dec 31 '25 09:12

foreline


1 Answers

Why multiple inheritance is forbidden in some/most programming languages is argued with the diamond problem http://en.wikipedia.org/wiki/Diamond_problem.

Put simple if you have a car that can swim and drive because it inherits from vehicle and boat what happens on execution of the move function!?

Try using interfaces and follow the Strategy pattern or State pattern.

like image 118
jonbros Avatar answered Jan 01 '26 22:01

jonbros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!