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?
views:
126answers:
5You're probably looking for: Multiple Inheritance in PHP.
It seems to be possible in Python.
Take a look at http://stackoverflow.com/questions/356128/can-i-extend-a-class-using-more-than-1-class-in-php
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?
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.