How to Use PHP Traits

PHP Traits are a great tool for code reuse. They allow developers to write methods that can be used in any number of classes, keeping your code DRY and more maintainable.

Define a PHP Trait

Traits are defined much in the same way as classes.

You’ll notice that we’re declaring a trait  rather than a class .

A PHP Trait Example

Let’s pretend we have a large number of classes related to film genres. Each class has public properties that we would like to return as either an array or JSON.

Now, we’ll create a trait that adds the methods we need and can be reused across all of our classes.

We add this trait to our class:

Putting it all together:

Output: