What are PHP Traits and how do they solve single inheritance limitations?
❓ Interview Prompt: Explain PHP Traits, horizontal code reuse across unrelated class hierarchies, and resolving method name collisions with insteadof and as.
Like Java, PHP enforces Single Inheritance: a class can only extend one parent class ('class Dog extends Animal'). However, in complex domains, you often need to share methods (like logging or UUID generation) across unrelated class hierarchies without duplicating code.
How Traits Work:
A Trait ('trait Loggable') enables horizontal code reuse. You inject traits into any class using the 'use' keyword inside the class body.
Resolving Method Collisions:
If two traits included in the same class define a method with the exact same name, PHP throws a fatal compile error! Resolve collisions using 'insteadof' (to choose which trait method to use) and 'as' (to alias conflicting methods).
Code Implementation Example
<?php
trait LoggerTrait {
public function log(string $msg): void { echo "[LOG] $msg
"; }
}
trait UuidTrait {
public function generateUuid(): string { return uniqid(); }
public function log(string $msg): void { echo "[UUID] $msg
"; }
}
class OrderService {
use LoggerTrait, UuidTrait {
LoggerTrait::log insteadof UuidTrait; // Choose LoggerTrait log method
UuidTrait::log as logUuid; // Alias UuidTrait log method
}
}Traits enable horizontal code reuse across unrelated classes in PHP. Resolve method collisions using insteadof and as keywords.