In PHP, a class can't inherit from more than one other class — multiple inheritance is not allowed. But what if you want to reuse methods in different classes? The answer is traits.
What is a Trait ?
A trait
is a way to reuse code in languages that don't support multiple inheritance. It lets you define methods and "inject" them into as many classes as you want, without inheritance.
Example
trait Logger {
public function log($message) {
echo "[LOG]: $message\n";
}
}
class Product {
use Logger;
public function save() {
$this->log("Product saved successfully.");
}
}
class User {
use Logger;
public function register() {
$this->log("User registered.");
}
}
Here, both Product
and User
can use the log()
method, even though they don’t extend the same parent class.
What if Two Traits Have the Same Method?
You can solve method conflicts using insteadof
and as
trait A {
public function speak() {
echo "Trait A\n";
}
}
trait B {
public function speak() {
echo "Trait B\n";
}
}
class Example {
use A, B {
B::speak insteadof A;
A::speak as speakFromA;
}
}
Now you can control which method is used.
Can Traits Have Properties ?
Yes, they can! But be careful. If two traits define properties with the same name, and you use both in the same class, PHP will throw an error.
trait Configurable {
protected $mode = 'dev';
}
Best Practices
Use traits for generic and reusable features (like logging, caching, validation, etc).
Avoid putting complex business logic inside traits — this can make testing and maintenance harder.
Use clear names for your traits:
HasLogger
,CanCache
,HandlesValidation
, etc.
Laravel Example
In Laravel, Traits are great for shared behavior between models:
trait HasUuid {
protected static function bootHasUuid()
{
static::creating(function ($model) {
$model->uuid = (string) \Str::uuid();
});
}
}
class Order extends Model {
use HasUuid;
}
Simple, powerful, and reusable.
Conclusion
Traits are a powerful tool for PHP developers. They help you keep your code clean, DRY (Don’t Repeat Yourself), and well organized.
If you don’t use traits yet in your daily work, give them a try. Your code will thank you. 😄