PHP 中的特征和摘要 Class 之间的区别
Difference between Trait and an Abstract Class in PHP
我最近遇到了 Traits in PHP and I'm trying to understand them. During my research I stumbled upon this Stack Overflow question: Traits vs. Interfaces。接受的答案提到以下内容:
An interface defines a set of methods that the implementing class must
implement.
When a trait is use'd the implementations of the methods come along
too--which doesn't happen in an Interface.
到目前为止还不错,但对我来说这听起来就像接口和抽象之间的区别 class。所以这对我提出了一个后续问题:
- PHP 中的 Trait 和 Abstract Class 有什么区别?
我知道我只能从一个抽象 class 扩展,另一方面可以使用任意数量的特征。但这真的是唯一的区别吗? traits 和它的用途我还是不太明白。
特性允许您在 class 和 之间共享代码,而不会强迫您进入特定的 class 层次结构 。假设您希望所有 classes 都具有方便的实用方法 foo($bar)
;没有特质你有两个选择:
- 在每个 class
中使用代码冗余单独实现它
- 继承自共同(抽象)祖先 class
这两种解决方案都不理想,各有不同的权衡。代码冗余显然是不可取的,并且从一个共同的祖先继承会使您的 class 层次结构设计不灵活。
Traits 通过让你在一个 trait 中实现 foo($bar)
来解决这个问题,每个 class 可以单独 "import",同时仍然允许你设计你的 class 层次结构业务逻辑要求,而不是语言要求。
不完全是...让我们为此目的引用官方文档:
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.
因此,Traits 用于组合目的,使 class 能够执行一些 logic/behavior。如果您从 another/abstract class 继承,通常是出于多态性的目的,您会得到一个独特的 inheritance/class 层次结构,这可能是理想的,也可能不是。
我认为这完全取决于上下文、体系结构以及您到底想做什么。
我最近遇到了 Traits in PHP and I'm trying to understand them. During my research I stumbled upon this Stack Overflow question: Traits vs. Interfaces。接受的答案提到以下内容:
An interface defines a set of methods that the implementing class must implement.
When a trait is use'd the implementations of the methods come along too--which doesn't happen in an Interface.
到目前为止还不错,但对我来说这听起来就像接口和抽象之间的区别 class。所以这对我提出了一个后续问题:
- PHP 中的 Trait 和 Abstract Class 有什么区别?
我知道我只能从一个抽象 class 扩展,另一方面可以使用任意数量的特征。但这真的是唯一的区别吗? traits 和它的用途我还是不太明白。
特性允许您在 class 和 之间共享代码,而不会强迫您进入特定的 class 层次结构 。假设您希望所有 classes 都具有方便的实用方法 foo($bar)
;没有特质你有两个选择:
- 在每个 class 中使用代码冗余单独实现它
- 继承自共同(抽象)祖先 class
这两种解决方案都不理想,各有不同的权衡。代码冗余显然是不可取的,并且从一个共同的祖先继承会使您的 class 层次结构设计不灵活。
Traits 通过让你在一个 trait 中实现 foo($bar)
来解决这个问题,每个 class 可以单独 "import",同时仍然允许你设计你的 class 层次结构业务逻辑要求,而不是语言要求。
不完全是...让我们为此目的引用官方文档:
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.
因此,Traits 用于组合目的,使 class 能够执行一些 logic/behavior。如果您从 another/abstract class 继承,通常是出于多态性的目的,您会得到一个独特的 inheritance/class 层次结构,这可能是理想的,也可能不是。
我认为这完全取决于上下文、体系结构以及您到底想做什么。