Traits
Prerequisites: Object-oriented programming in depth
A trait shares method implementations across unrelated classes —
PHP's answer to not having multiple inheritance, letting you mix in
reusable behavior without a shared base class.
trait Loggable
{
public function log(string $message): void
{
echo "[" . static::class . "] $message";
}
}
class Order
{
use Loggable;
}
class User
{
use Loggable;
}
(new Order())->log("Created"); // [Order] Created
Common mistakes
- Overusing traits for anything reusable — if the behavior and the class share a genuine "is-a" relationship, prefer inheritance or an interface; traits shine for cross-cutting behavior (like logging) that doesn't fit a class hierarchy.