Traits — Horizontal Reuse (PHP 5.4)
TL;DR
PHP 5.4 traits enable horizontal code reuse — mixins for PHP classes that can't use multiple inheritance. Use sparingly; prefer composition over trait overuse.
Explanation
Traits (PHP 5.4) allow including method groups in multiple classes: trait Timestampable { public function touch(): void { $this->updatedAt = new DateTime(); } }. Multiple traits per class with use Trait1, Trait2. Conflict resolution: insteadof and as operators. Traits can define abstract methods (requiring implementing class to provide them), properties, and constants (PHP 8.2). Downsides: traits create implicit coupling, make code harder to test (no mock boundary), and can lead to 'trait soup'. Prefer composition (inject a collaborator) when the trait becomes large or complex.
Common Misconception
✗ Traits are equivalent to interfaces — traits provide implementation (methods), interfaces define contracts. Traits are reuse mechanisms, not type contracts.
Why It Matters
Traits solve the specific problem of sharing implementation across unrelated class hierarchies — but overuse creates hidden coupling that's worse than duplication.
Common Mistakes
- Overusing traits as a workaround for lack of multiple inheritance — prefer composition.
- Traits that depend on specific properties of the host class — tight implicit coupling.
- Not resolving trait conflicts explicitly when using multiple traits with same method names.
Code Examples
✗ Vulnerable
// Trait depending on host class internals — implicit coupling:
trait Logger {
public function log(): void {
// Assumes $this->name exists in host class
echo $this->name . ' logged';
}
}
✓ Fixed
trait Timestampable {
private ?DateTime $updatedAt = null;
public function touch(): void {
$this->updatedAt = new DateTime();
}
public function getUpdatedAt(): ?DateTime {
return $this->updatedAt;
}
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
17
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Amazonbot 6
Unknown AI 3
Perplexity 2
Google 2
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 12
crawler_json 1
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Medium
⚡ Quick Fix
Use traits for cross-cutting concerns (logging, timestamping). Keep traits small and self-contained. Prefer composition for complex shared behaviour.
📦 Applies To
PHP 5.4+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
use [A-Z][a-zA-Z]+;
Auto-detectable:
✗ No
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Medium
Context: Class
Tests: Update