🐘 PHP Intermediate

What is a PHP trait?

Why Interviewers Ask This

This tests whether you can apply PHP knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

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.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last PHP project, I used this when...' immediately makes your answer more credible and memorable.