PHP › Traits
What is a trait in PHP, and how does it let you share a set of methods across multiple unrelated classes without using traditional inheritance?
BeginnerAnswer
A trait is a mechanism for reusing a set of methods across multiple classes that are not necessarily related to each other through a normal parent child inheritance relationship, and a class incorporates a trait's methods by using the use keyword followed by the trait's name inside the class body, which effectively copies the trait's methods directly into that class as if they had been written there originally, letting completely unrelated classes share the exact same reusable functionality without needing to force an artificial shared parent class between them.
trait Loggable {
public function log(string $message): void {
echo date('Y-m-d H:i:s') . ': ' . $message;
}
}
class Order {
use Loggable;
}Real-world example Both an Order class and a completely unrelated PaymentProcessor class use the same Loggable trait to gain identical logging functionality, without needing to share any common parent class between them at all.