Why does PHP have abstract classes if you can use an interface and traits?

后端 未结 3 985
孤独总比滥情好
孤独总比滥情好 2021-01-31 19:47

Earlier today I was doing research on PHP\'s abstract classes, interfaces, and traits.

As far as I can tell, an abstract class says \"anything using me will be using the

3条回答
  •  孤街浪徒
    2021-01-31 20:36

    I think there is some philosophical difference on how and when to use them.

    You said :

    1. abstract classes: "anything using me will be using these methods and attributes"
    2. interfaces:"anything using me must have these methods and attributes"
    3. traits: "anything using me will also have these methods and attributes".

    If you focus on your own wordings it makes sense.

    Abstract Classes are in reality define things that are abstract e.g Vehicle is an abstract thing until or unless its materialized in the form of a car or a bike . Neither interface define it nor traits.

    Interfaces compliment the class inheritance functionality where a class inherits from multiple classes(only certain languages provide multiple inheritance e.g C/C++). Interfaces , as names suggest focus on the INTERFACE , and not the implementation of the interface method in class which is implementing it. It makes classes PLUG & PLAYABLE so everyone should follow a standard. If you further read about factory and adapter pattern on OOP you will understand it.

    Traits have implementation/functionality that is not bound to specific classes.Instead it could be found across different classes. Its like a gene in genetics which stays mute in parents and appear only in certain children. Or to be concise selective inheritance but not bound to single class. So it provides a way much better code-reuse

    Edit Interface + Trait != Abstract Class , because when using Trait inheritance is selective as you select specific trait to use and while using Abstract Class inheritance is mandatory or dictated by parent class you don't have freedom!

提交回复
热议问题