我最近一直在努力学习 PHP,但我发现自己对 trait 很着迷。我理解水平代码重用的概念,并且不想一定要从抽象类继承。我不明白的是:使用特征与接口(interface)之间的关键区别是什么?
我曾尝试寻找解释何时使用其中一个的不错的博客文章或文章,但到目前为止我发现的示例看起来非常相似,以至于完全相同。
最佳答案
接口(interface)定义了一组方法,实现类 必须实现。
当特征是 use
方法的实现也会出现——这不会发生在 Interface
中.
这是最大的不同。
来自 Horizontal Reuse for PHP RFC :
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
关于php - 特性与接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9205083/