Using traits
If you have ever done any C programming, you are perhaps familiar with macros. A macro is a predefined block of code that expands at the line indicated. In a similar manner, traits can contain blocks of code that are copied and pasted into a class at the line indicated by the PHP interpreter.
How to do it...
- Traits are identified with the keyword
trait
, and can contain properties and/or methods. You may have noticed duplication of code when examining the previous recipe featuring theCountryList
andCustomerList
classes. In this example, we will re-factor the two classes, and move the functionality of thelist()
method into aTrait
. Notice that thelist()
method is the same in both classes. - Traits are used in situations where there is ...
Get PHP 7 Programming Cookbook 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.