Why PHP Trait can't implement interfaces?

后端 未结 4 1158
暗喜
暗喜 2020-12-23 10:56

I\'m wondering why PHP Trait (PHP 5.4) cannot implement interfaces.

Update from user1460043\'s answer => ...cannot require class which uses it to implement a

4条回答
  •  一向
    一向 (楼主)
    2020-12-23 11:27

    [...] to "design" in the code that every class that want to use my trait have to implement the interface. That would allow the Trait to use class methods defined by the interface and be sure they are existing in the class.

    This sounds very reasonable and I would not say that there has to be anything wrong with your design. Traits have been suggested with this idea in mind, see the second point here:

    • A trait provides a set of methods that implement behaviour.
    • A trait requires a set of methods that serve as parameters for the provided behaviour.
    • [...]

    Schärli et al, Traits: Composable Units of Behaviour, ECOOP’2003, LNCS 2743, pp. 248–274, Springer Verlag, 2003, Page 2

    So it would be maybe more appropriate to say that you want a trait to require an interface, not to "implement" it.

    I do not see a reason why it should be impossible to have this "trait requires (its consumer classes to implement) an interface" feature in PHP, but currently it seems to be missing.

    As @Danack notes in his answer, you can use abstract functions in the trait to "require" them from classes that use the trait. Unfortunately you can not do this with private functions.

提交回复
热议问题