Difference between Trait and an Abstract Class in PHP

前端 未结 2 1766
太阳男子
太阳男子 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:54

    Traits allow you to share code between your classes without forcing you into a specific class hierarchy. Say you want all your classes to have the convenient utility method foo($bar); without traits you have two choices:

    • implement it individually with code redundancy in each class
    • inherit from a common (abstract) ancestor class

    Both solution aren't ideal, each with their different tradeoffs. Code redundancy is obviously undesirable, and inheriting from a common ancestor makes your class hierarchy design inflexible.

    Traits solve this problem by letting you implement foo($bar) in a trait which each class can "import" individually, while still allowing you to design your class hierarchy according to business logic requirements, not language necessities.

提交回复
热议问题