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.
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 duplication of code between classes. Please note, however, that the conventional approach to creating an abstract class and extending it might have certain advantages over using traits. Traits cannot be used to identify a line of inheritance, whereas...