特性与PHP中的抽象类之间的区别 [英] Difference between Trait and an Abstract Class in PHP
问题描述
我最近在PHP中遇到了特质,我正在尝试了解他们。在研究期间,我偶然发现了这个堆栈溢出问题:特质与接口 。接受的答案提到以下内容:
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 answer mentions the following:
接口定义了实现类必须
实现的一组方法。
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.
到目前为止,还算不错,但这听起来完全像是接口和抽象类之间的区别。因此,这给我提出了一个后续问题:
So far so good but this sounds exactly like the difference between an interface and an abstract class to me. So this raises a follow-up question for me:
- PHP中的Trait和Abstract类有什么区别?
我知道我只能从一个抽象类扩展,而另一方面可以使用任意数量的特征。但这真的是唯一的区别吗?我仍然不完全了解特征及其用途。
I am aware that I can extend from only one abstract class and on the other hand use any amount of traits. But is this really the only difference? I still don't completely understand traits and its use.
推荐答案
特质允许您在类之间之间共享代码强迫您进入特定的班级层次结构。假设您希望所有类都具有便捷的实用程序方法 foo($ bar)
;没有特征的您有两种选择:
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:
- 在每个类中使用代码冗余分别实现它
- 继承来自普通(抽象)祖先类
这两种解决方案都不理想,每个方案都有不同的权衡。代码冗余显然是不可取的,并且从一个共同的祖先继承使您的类层次结构设计变得不灵活。
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.
特质通过让您实现 foo( $ bar)
的特征,每个类可以分别导入该特征,同时仍然允许您根据业务逻辑要求(而不是语言必要性)来设计类层次结构。
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.
这篇关于特性与PHP中的抽象类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!