🐘 PHP Intermediate

What is a PHP trait?

Answer

A trait is a mechanism for code reuse in single-inheritance languages like PHP. Traits allow you to include methods (and abstract methods) in multiple classes without inheritance. Declare with trait Loggable { public function log(): void { ... } } and use with use Loggable inside a class. A class can use multiple traits. Traits can define abstract methods (forcing the using class to implement them), properties, and even use other traits. Conflict resolution: if two traits define the same method, you must resolve the conflict explicitly with the insteadof and as operators. Traits are "copied-and-pasted" into the class at compile time — they are not independently instantiatable.