Why doesn’t PHP directly introduce multiple inheritance but traits?
Why doesn’t PHP directly introduce multiple inheritance but traits?
There are many discussions on the Internet,
wiki introduction about 多重继承
: https://zh.wikipedia.org/wiki/Multiple inheritance
If ClassA
and ClassB
have a common eat()
, which one do you inherit?
Multiple inheritance is useful as a developer in many situations, but it greatly increases complexity for both the compiler developer and the programmer. A problem occurs when two parent classes have data members or methods with the same name. It is difficult to resolve being referenced by a subclass. In addition, when two parent classes inherit from the same base class, 钻石问题
is formed.
Multiple inheritance has a greater impact on design patterns. . Bar
Multiple inheritance goes against many design patterns and is not adopted by most languages.
Although trait
has many similarities with multiple inheritance, it effectively avoids the problems that may arise with multiple inheritance and allows design ideas from other languages to be easily applied to php
.