PHP 中 Trait 和抽象类的区别 [英] Difference between Trait and an Abstract Class in PHP

查看:30
本文介绍了PHP 中 Trait 和抽象类的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 PHP 中遇到了 Traits 并且我正在尝试去了解他们.在我的研究中,我偶然发现了这个堆栈溢出问题:特性与接口.接受的答案提到了以下内容:

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 中的特征和抽象类有什么区别?

我知道我只能从一个抽象类扩展,另一方面可以使用任意数量的特征.但这真的是唯一的区别吗?我仍然不完全了解特征及其用途.

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.

Traits 通过让您在每个类可以单独导入"的 trait 中实现 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 中 Trait 和抽象类的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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