What are Traits?

Traits are available in PHP language since 5.4. version. The need for traits is because of PHP limitations of single inheritance. A class cannot extend multiple classes. You could argue that you could simply use multiple interfaces but what if you wanted to have actual implementation of methods and not just blueprints? Well then you’d have to resort to using traits.

Traits are actually really simple. They start with trait keyword and then you just write your methods which you plan on reusing. Traits like abstract classes cannot be instantiated. They can only be used within classes.

Using traits helps you to adhere to DRY principles so let’s give a few examples.

Example: Using trait

Example: Using multiple traits

Read More