In this chapter
We'll learn traits — PHP's way of sharing methods and properties between unrelated classes — how a class uses several traits, how to settle conflicts with insteadof and as, the precedence rules between a class, its traits and its parent, and how traits compare with mixins in Ruby and Python.
The Problem in Real Life
Booking, Customer and Barber all have the same three members: a createdAt property, a touch() method that updates an updatedAt time, and a log() method. The code is copied into each class, and the Barber copy has an older version of touch() that forgets to set updatedAt.
Inheritance doesn't fit: a customer is not a booking, and a barber isn't either. And a class can have only one parent anyway.
These three classes share code but aren't related. Where does code like that go?
Mia
Copying Methods vs. Using a Trait
Same code, unrelated classes
Timestamps and logging belong in many classes that share nothing else — so inheritance is the wrong tool.
Copied in by PHP
A trait's methods are copied into each class that uses it, as if you'd written them there — once, in one place.
When two traits clash
Two traits with a method of the same name need an explicit decision: which one wins.
Traits
Sharing code sideways: inheritance shares code down a family of classes. Traits share it sideways, between classes that aren't related at all. This chapter covers:
- Traits: declaring them and using them in a class.
- Several traits: composing a class from more than one.
- Conflicts: two traits with the same method name —
insteadofandas. - Precedence: what wins between the class, its traits and its parent.
Traits: trait HasTimestamps { ... } looks like a class: it can contain properties, methods (also abstract and static ones) and, since PHP 8.2, constants. But you can't create an object from it. Instead, a class writes use HasTimestamps; inside its body, and PHP copies the trait's members into the class, as if they had been written there. Booking, Customer and Barber each use HasTimestamps;, and the one touch() lives in one file; the Barber bug disappears with the copy. Trait names usually describe a capability: HasTimestamps, Loggable, SoftDeletes — Laravel ships dozens of these. The diagram below shows one trait copied into three unrelated classes.
One trait, copied into unrelated classes
trait HasTimestamps
createdAt · updatedAt · touch()
class Booking
use HasTimestamps;
class Customer
use HasTimestamps;
class Barber
use HasTimestamps;
Each class has its own touch()
but the code exists once, in the trait
<?phpdeclare(strict_types=1);trait HasTimestamps{public string $createdAt = "2026-11-01 09:00";public ?string $updatedAt = null;public function touch(string $now): void{$this->updatedAt = $now;}}class Booking{use HasTimestamps;}class Barber{use HasTimestamps;}$booking = new Booking();$ben = new Barber();$booking->touch("2026-11-01 10:15");$ben->touch("2026-11-01 11:00");echo $booking->updatedAt, " / ", $ben->updatedAt, "\n"; // 2026-11-01 10:15 / 2026-11-01 11:00
Several traits: a class can use as many traits as it needs, use HasTimestamps, Loggable;, and traits can use other traits. That's how PHP covers what other languages do with mixins. In Ruby, a module is mixed into a class with include; in Python, small "mixin" classes are combined through multiple inheritance (chapter 7); Scala calls them traits too. PHP's traits play the same role without multiple inheritance: the methods are copied in, and the class still has one parent. Note that a trait is not a type: $booking instanceof HasTimestamps is always false. When you need a type, add an interface, and let the trait provide its methods.
<?phpdeclare(strict_types=1);interface Loggable{public function log(string $line): void;}trait LogsToArray // provides the interface's method{public array $lines = [];public function log(string $line): void{$this->lines[] = static::class . ": " . $line;}}class Customer implements Loggable{use LogsToArray;}$clare = new Customer();$clare->log("phone changed");echo $clare->lines[0], "\n"; // Customer: phone changedvar_dump($clare instanceof Loggable); // bool(true): the interface is a typevar_dump($clare instanceof LogsToArray); // bool(false): the trait is not
# Ruby — a module is "mixed in" to a class with includemodule HasTimestampsdef touch(now)@updated_at = nowendendclass Bookinginclude HasTimestampsendBooking.new.touch("2026-11-01 10:15")
Conflicts: if two traits used by the same class both have a method called log(), PHP refuses to guess: it's a fatal error ("Trait method … has not been applied … because of collision"). You decide in a block after use: Loggable::log insteadof Auditable; picks one version, and Auditable::log as audit; keeps the other under a new name. as can also change a trait method's visibility: log as protected;.
<?phptrait Loggable{public function log(): string{return "log line";}}trait Auditable{public function log(): string{return "audit entry";}}class Booking{use Loggable, Auditable {Loggable::log insteadof Auditable; // log() means Loggable's versionAuditable::log as audit; // Auditable's is kept as audit()}}$booking = new Booking();echo $booking->log(), " / ", $booking->audit(), "\n"; // log line / audit entry// Without the block: Fatal error: Trait method Auditable::log has not been applied// as Booking::log, because of collision with Loggable::log
Precedence: when the same method name comes from several places, PHP follows a fixed order: a method written in the class itself wins over a trait's method, and a trait's method wins over one inherited from the parent class. So a class can always override a trait's method by writing its own, and call the trait's version through an as alias if it needs it. The table below sums up the rules. The diagram below shows where PHP looks, in order.
| Situation | Syntax or rule |
|---|---|
| Use a trait | class Booking { use HasTimestamps; } |
| Use several | use HasTimestamps, Loggable; |
| Two traits, same method | use A, B { A::log insteadof B; } |
| Keep the other one too | B::log as audit; |
| Change visibility | use A { log as protected; } |
| Who wins? | The class's own method > the trait's > the parent's |
| Is it a type? | No: instanceof is false — add an interface for that |
Which label() runs? PHP looks in this order and stops at the first match
1. Booking's own method
class Booking { public function label() … }
2. The trait's method
use Labels; — only if the class has none
3. The parent's method
class Model — only if neither has one
<?phpclass Model{public function label(): string { return "from the parent"; }public function kind(): string { return "from the parent"; }}trait Labels{public function label(): string { return "from the trait"; }public function kind(): string { return "from the trait"; }}class Booking extends Model{use Labels;public function label(): string { return "from the class"; }}$b = new Booking();echo $b->label(), " | ", $b->kind(), "\n";// from the class | from the trait
When to use traits: traits are for small, self-contained pieces of behaviour that many classes need — timestamps, logging, a toArray() helper. Keep them small and independent of the class's details. A trait that reaches into properties it hopes the class has, or that holds half of the class's real logic, makes code hard to follow, because the behaviour is spread over files that don't show up in the class's parent or interfaces. When in doubt, prefer composition: put the shared code in its own class and give that class to the others (chapter 12).
Key Takeaway
A trait is a bundle of methods (and properties and constants) that PHP copies into every class that uses it — code sharing between unrelated classes, PHP's version of mixins (Ruby modules, Python mixins). A class can use several traits; conflicts are settled with insteadof and renamed with as. The class's own methods beat trait methods, which beat inherited ones. A trait is not a type — pair it with an interface — and should stay small; prefer composition for anything bigger.
Why This Matters
Traits let unrelated classes share small behaviours without forcing a fake family tree on them — and without PHP needing multiple inheritance. Timestamps, logging and soft deletes written once, used by many classes, fixed in one place.
You'll meet traits constantly in Laravel: HasFactory, SoftDeletes, Notifiable on every model. Knowing that they're copied in, that they aren't types, and who wins in a conflict makes framework code readable instead of magical.
Timestamps and logging are traits now, and the Barber bug is gone with its copy. Then Olivia looks at the price code and sighs: total() is a long if ($booking instanceof GroupBooking) ... elseif ($booking instanceof GiftBooking) ..., and the new gift bookings come out at the full price. The class knows the price rule, but someone else is asking it what it is. That's the next chapter: encapsulation, abstraction and polymorphism.
