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 the
CustomerListclasses. In this example, we will re-factor the two classes, and move the functionality of the
list()method into a
Trait. Notice that the
list()method is the same in both classes.
- Traits are used in situations where there is ...