Difference between Trait and an Abstract Class in PHP

前端 未结 2 1708
太阳男子
太阳男子 2021-01-31 14:59

I recently came across Traits in PHP and I\'m trying to understand them. During my research I stumbled upon this Stack Overflow question: Traits vs. Interfaces. The accepted ans

2条回答
  •  醉话见心
    2021-01-31 15:27

    Not exactly... Let's quote official documentation for this purpose:

    A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

    So Traits are used for composition purposes to enable the class to perform some logic/behavior. If you're inheriting from another/abstract class, it's usually for purposes of polymorphism and you get a distinct inheritance/class hierarchy, which may or may not be desirable.

    I think it all depends on the context, on the architecture and on what exactly are you trying to do.

提交回复
热议问题