Traits vs. interfaces(特性与接口)
问题描述
我最近一直在努力学习 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.
这篇关于特性与接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:特性与接口


- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01