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

后端 未结 3 988
孤独总比滥情好
孤独总比滥情好 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:16

    When you use traits, you simply require a given class to implement some methods.

    You won't inherit any properties or methods and you won't force the object into any inheritance tree.

    Thus you can have several completely unrelated classes using the same trait, just to guarantee any object of theses classes will support a given method.

    this is how PHP does the famous Mixins. Basically a Mixin is just a class that can share common traits with several other classes. Traits allow to enforce that constraint on the methods of classes, independently of the way these classes inherit from each other or not.

    Instead of having to do multiple inheritances to the point of silliness when you want a class to combine the behaviour of two parents, you can use traits to obtain the same result without the hassle of ineriting a bunch of unwanted other things.

提交回复
热议问题