What are the possible use cases for Traits in PHP?

Possible duplicate:
php traits - examples or best real world examples?

In what situations can traits be used in PHP? I have a pretty good general idea, but I can’t imagine how to use them in the application I wrote, but it could be because at that time he didn’t need traits.

One scenario I understood needs traits:

  • Events. Instead of having one class that implements an observer pattern and allowing all other classes to inherit it, just make it a sign and let classes that want to fire events or subscribe to use this sign. For example, the Yii framework does this incorrectly by implementing material in the CComponent class rather than using Trait.

Basically, functionality that can be shared between classes, but can be distributed across several class hierarchies, should use traits. What other scenarios can use traits rather than an event system?

+6
source share
1 answer

The problem that Trait Addresses are similar to those that Java addresses with interfaces is how to enforce common behavior (represented by interfaces) among classes that are not part of the same class hierarchy.

With languages ​​like C ++ that only have inheritance, for two objects from two different classes that should be used in the same context, requiring the same behavior, the two classes should have been from the same hierarchy. Sometimes this meant creating completely artificial hierarchies to allow the use of objects from different classes in the same context.

Java solved this problem through interfaces - an interface is essentially a contract governing the provision of behavior, so an object of one class can be replaced with an object of a separate class, because it promises the same behavior - an interface. But they should not be from the same hierarchy.

PHP traits embody this idea. A characteristic is a kind of interface, a set of behavior that a class contains, so that it can be used in a context that requires such behavior. Thus, any example Java interface should be carried over to the example of PHP Traits. PHP traits are slightly different from Java interfaces, though, since Traits can contain complete function definitions, while Java interfaces can only contain declarations (typical PHP features)

-4
source

Source: https://habr.com/ru/post/909611/


All Articles