PHP › OOP
How does PHP handle multiple inheritance limitations, and how do traits provide a mechanism for sharing reusable code across multiple unrelated class hierarchies?
AdvancedAnswer
PHP classes can only extend a single parent class, meaning true multiple inheritance is not supported, but traits provide a mechanism for horizontally sharing reusable methods across multiple, otherwise unrelated classes, letting you compose shared behavior into a class using the use keyword within the class body, effectively providing many of the code reuse benefits of multiple inheritance without the complexity and ambiguity issues that true multiple inheritance can introduce.
trait Loggable {
public function log($message) { echo "[LOG] $message"; }
}
class OrderService {
use Loggable;
}
class PaymentService {
use Loggable;
}Real-world example Two otherwise unrelated classes, OrderService and PaymentService, both incorporate the exact same logging functionality by using a shared Loggable trait, avoiding code duplication despite neither class extending a common parent class.