Traits
We mentioned previously that PHP is a single inheritance language. We cannot use the extends
keyword to extend multiple classes in PHP. This very feature is actually a rare commodity only a handful of programming languages support, such as C++. For better or worse, multiple inheritance allows some interesting tinkering with our code structures.
The PHP Traits provide a mechanism by which we can achieve these structures, either in the context of code reuse or the grouping of functionality. The trait
keyword is used to declare a Trait, as follows:
<?php trait Formatter { // Trait body }
The body of a Trait can be pretty much anything we would put in a class. While they resemble classes, we cannot instantiate a Trait itself. We can only use the Trait from another class. To do so, we employ the use
keyword within the class body, as shown in the following example:
class Ups { use Formatter; // Class body (properties & methods) }
To better understand how Traits can be helpful...