PHP Traits: What, Why, and How

Long-time ago in a far far away PHPland, One of the problems developers faced was the fact that a class can only inherit from one other class.

Traits arrived in PHP 5.4 on a mission to save the day, allowing for code reuse across multiple classes irrespective of the hierarchies. The result – reduced inheritance limitation.

The purpose of a Trait is to group several methods and make them available to a class. Traits can be thought of as a helper class.

Traits are included in classes via the keyword use i.e use UserService. We can also include multiple Traits via the keyword use UserService, NotificatioService. Like an abstract class, it is not possible to instantiate a Trait on its own and so constructor functions do not work.

Original Problem Visualized

Suppose you have the classes specified below, but you need access to the UserService to get the currentUser to send an email or notification. Its likely you have to implement the UserService for each class.

Or find another way. Traits solves this problem.

The Traits Solution

Abstract and static methods can be defined inside a Trait. With an abstract method the class using said Trait is forced to implement the method or else a fatal error is thrown.

A Trait can also be composed of other Traits. (See example below.)

The insteadof keyword allows use to specify method to use in the scenario where a composed Trait has child Traits with the same method and as to specify and alias name.

As is in the examples above we can use the price stated in food rather than drink by:

food::price insteadof drink

In Conclusion

Traits are a very powerful tool because it encourages code reuse however it can be easily be abused. Try to follow the Single Responsibility Principle and well all live happily ever after.

Related Posts