duanlan8763 2016-09-13 09:25
浏览 40
已采纳

PHP中特征与抽象类的区别

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:

  • What is the difference between a Trait and an Abstract Class in 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.

  • 写回答

2条回答 默认 最新

  • duanlu4371 2016-09-13 09:32
    关注

    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:

    • implement it individually with code redundancy in each class
    • inherit from a common (abstract) ancestor class

    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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容