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:

<?phptrait 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 ...

Get Mastering PHP 7 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.