tags:

views:

126

answers:

5

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?

+6  A: 

You're probably looking for: Multiple Inheritance in PHP.

It seems to be possible in Python.

kovshenin
+1  A: 

Is it a bad practice? If so, what are alternatives?

Unless the language is specifically designed for it, yes. Consider, you have two classes, A and B. Both classes provide a public method foo() which have identical signatures (not hard in PHP). Now, you make a class C which extends both A and B.

Now, you call C.foo(). Without explicit instructions, how does the interpreter know which version of foo() to call?

EricBoersma
It should raise a compilation error like: method foo() already defined in class B. I think it's up for programmer to watch methods of parent classes conflicts, and not up for 'smart' interpreter.
SaltLake
@SaltLake: That's how C++ does it. PHP chose to organize things more similarly to Java, and that was a valid design decision. Both sides have merits, but unfortunately we can't have our cake and eat it too.
EricBoersma
+4  A: 

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.

jonbros
And it's not just methods, but data too. Consider $max_speed for a hybrid derived from 'car' and 'boat': is it max speed of the car or the boat? Should the fields be merged or should they exist separately? And then how to access this field if there are 2 copies of it?
mojuba
+1  A: 

It's not supported by PHP. It can however be simulated using runkit, APD or by just overriding __call and __get to simulate inheritance from multiple classes. Symfony (and I seldomly recommand that) also provides "sfMixin" or "sfMixer" for multiple inheritance.

mario