特征与接口 [英] Traits vs. Interfaces

查看:91
本文介绍了特征与接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在尝试研究PHP,我发现自己陷入了特征。我理解水平代码重用的概念,不希望必须从抽象类继承。我不明白的是,使用特征与接口之间的关键区别是什么?

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.

那里的任何人都能分享他们对此的意见/看法吗?

Could anyone out there share their opinion/view on this?

推荐答案

接口定义了实现类必须实现的一组方法。

An interface defines a set of methods that the implementing class must implement.

当特征是时,使用'd方法的实现也会出现 - 这不会发生在<$ c $中c>界面。

When a trait is use'd the implementations of the methods come along too--which doesn't happen in an Interface.

这是最大的区别。

来自< a href =https://wiki.php.net/rfc/horizo​​ntalreuse =noreferrer> 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.

这篇关于特征与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆