我最近一直在努力学习 PHP,但我发现自己沉迷于 trait.我理解水平代码重用的概念,并且不想一定要从抽象类继承.我不明白的是:使用特性和接口之间的关键区别是什么?
I've been trying to study up on PHP lately, and I find myself getting hung up on traits. I understand the concept of horizontal code reuse and not wanting to necessarily inherit from an abstract class. What I don't understand is: What is the crucial difference between using traits versus interfaces?
我曾尝试寻找解释何时使用一种或另一种的不错的博客文章或文章,但到目前为止我发现的示例看起来非常相似以至于完全相同.
I've tried searching for a decent blog post or article explaining when to use one or the other, but the examples I've found so far seem so similar as to be identical.
一个接口定义了一组实现类必须实现的方法.
An interface defines a set of methods that the implementing class must implement.
当特征被use
使用时,方法的实现也会随之而来——这不会发生在Interface
中.
When a trait is use
'd the implementations of the methods come along too--which doesn't happen in an Interface
.
这是最大的不同.
来自 PHP RFC 的水平重用:
Traits 是一种在 PHP 等单继承语言中重用代码的机制.Trait 旨在通过使开发人员能够在位于不同类层次结构中的多个独立类中自由重用方法集来减少单继承的一些限制.
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.
这篇关于特性与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!