PHP: Why isn't it possible to extend more than one class?
I've faced a situation when I want to extend two parent classes, but php does not allow this.
Why I can'textend
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?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.
You're probably looking for: Multiple Inheritance in PHP.
It seems to be possible in Python.
Take a look at 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?
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.
Separate classes implementing the same method is not a good argument against multiple inheritance, as currently multiple interfaces can be implemented. You just can't implement two interfaces with the same method. Quote from http://www.php.net/manual/en/language.oop5.interfaces.php: "A class cannot implement two interfaces that share function names, since it would cause ambiguity."
I know this question is 2 years old but I've only just had the same problem. My work-around is this: if you have one regular class and two abstracts and want to extend both, e.g abstract class AbstractOne
and abstract class AbstractTwo
, you can say:
abstract class AbstractOne extends AbstractTwo {
}
Then add to the main class like this:
class MyMainClass extends AbstractOne {
}
This way, it inherits both AbstractOne and AbstractTwo.
精彩评论