Traits
Traits are a horizontal code reuse mechanism in PHP. While inheritance shares behavior vertically through a parent-child relationship, traits allow multiple unrelated classes to reuse the same methods without extending a common base class. A trait is defined using the trait keyword and can contain concrete methods and abstract methods. Trait methods may use any visibility modifier: public, protected, or private.
A class uses a trait via the use keyword inside the class body. When a trait is used, its methods are effectively inserted into the class at compile time, behaving as if they were written directly in that class. This means the class can call trait methods normally, and trait methods can access the class context through $this.
Multiple classes can use the same trait, which prevents duplicating shared logic across different parts of an application. This is especially useful when classes are not in the same inheritance chain but still need common behavior.
A single class can also use multiple traits by separating them with commas in the use statement. This allows composable behavior – a class can aggregate capabilities from different traits instead of inheriting everything from a single parent.
Traits complement abstract classes and interfaces rather than replace them. Interfaces define contracts (what must exist). Abstract classes define shared structure and partially implemented logic within a hierarchy. Traits focus purely on reusable behavior that can be mixed into any class regardless of its inheritance structure.
In short:
Traits provide reusable behavior without forcing inheritance.
Interfaces enforce capability contracts.
Abstract classes enforce structure within a hierarchy.