PHP Traits intended use is to reduce code duplication and increase code reuse. If you have the same methods across classes then it is best to traits. To understand PHP Traits much easier, think of it as “copy and paste” where the traits code are inserted to the implementing class at compile time.
Use the trait keyword to create a trait, and use the use keyword within the class to insert the trait.
Method precedence
Overriding Trait Methods
Developers can override any trait methods by creating the same method name within the class.
Overriding Parent Class Using Trait Methods In Child Class
Trait methods will override any methods of the base class if the child class use it.
Conflicting method names and properties
When implementing multiple traits, same name methods will cause a conflict. There are two ways to get around this using the insteadof operator and as operator.
insteadof operator
The insteadof operator lets you specify which method to run when there is a conflict between the method names.
as operator
The as operator lets use alias the method to a different name.
Composing traits within other traits
Developers can also use traits within traits.
Properties within Traits
The recommended way of addressing properties within traits is by having a setter method within the trait.
Static properties and methods within traits
Traits can also have static properties, static methods and static variables. Unlike inheritance static properties are independent to the class that implements the trait. Unlike inheritance where static properties are shared.
Comparing Inheritance & traits
Traits are best used if you want to share a method where inheritance is not applicable (is-a relationship).