Traits: Horizontal Reuse

Traits: Horizontal Reuse in PHP: --- An old-fashioned back office keeps a rack of rubber stamps: one that prints "RECEIVED" with a date wheel, one that prints…


The Analogy: The Set of Rubber Stamps in the Back Office

An old-fashioned back office keeps a rack of rubber stamps: one that prints "RECEIVED" with a date wheel, one that prints "PAID", one that stamps the company crest. These stamps are not documents themselves and they are not filed anywhere -- they are reusable marks that can be pressed onto any form that needs them. An invoice gets the crest and the "PAID" stamp; a delivery note gets the crest and "RECEIVED". The same "PAID" stamp is pressed onto hundreds of different documents, none of which are related to each other, because the stamp is a unit of marking that travels independently of the documents it lands on.

That is a trait. A trait is a bundle of methods (and properties) that is not a class in its own right and cannot be instantiated on its own -- it exists purely to be stamped into the classes that need its behaviour. Where inheritance is vertical (a subclass is a kind of its parent), a trait is horizontal: it drops the same capability into classes that are otherwise unrelated and share no parent. An Article, a Comment, and a User might all need "remember when I was last touched", so a Timestamped trait is stamped into each -- no forced common ancestor, just the shared mark pressed where it is wanted.

The rack solves a problem single inheritance cannot. A document can only be one kind of document, but it can carry many stamps. Likewise a PHP class extends only one parent, but it can use many traits, composing behaviour from several sources. This is how PHP offers horizontal code reuse without multiple inheritance: the class stays a single kind of thing while gathering methods from as many traits as it likes, each trait a self-contained mark of capability.

The failure mode is two stamps that both want the same spot. If the "PAID" stamp and an imported "SETTLED" stamp both try to print in the amount box, pressing both leaves an unreadable smudge and the clerk cannot tell what the document says. In PHP, when two traits provide a method of the same name, the class does not silently pick one -- it is a fatal error until you resolve the clash explicitly with insteadof and as. And because a trait's methods are copied into the class as if written there, a trait that quietly assumes a property exists on its host can compile fine yet break the moment it is stamped onto a class that lacks it. Traits give reuse without a shared ancestor, but they also give up the compiler's help in keeping their assumptions honest.


Syntax or Core Structure

A trait is declared like a class but with the trait keyword, and a class pulls it in with use. The trait's methods and properties then behave exactly as if they had been written in the class itself.

<?php
declare(strict_types=1);

trait Timestamped {
    private ?string $touchedAt = null;

    public function touch(string $when): void {
        $this->touchedAt = $when;
    }

    public function touchedAt(): string {
        return $this->touchedAt ?? 'never';
    }
}

class Article {
    use Timestamped;
    public function __construct(public readonly string $title) {}
}

$a = new Article('Hello');
echo $a->touchedAt(), "\n";
$a->touch('2026-01-01');
echo $a->touchedAt(), "\n";

Output:

never
2026-01-01

Article gains touch(), touchedAt(), and the private $touchedAt property purely by stamping in the Timestamped trait -- it did not extend anything. Before touch is called, touchedAt() returns never via the null coalescing fallback; after, it returns the stored date. The trait's members are genuinely part of Article now, with full access to $this, which is why the same trait can be stamped into a Comment or User class to give each the identical capability with no shared parent.


Technical Depth: Composition, Conflicts, and What Traits Are Not

Three tools, three jobs

Traits, interfaces, and inheritance are easy to confuse because all three relate classes to shared behaviour. The table separates them.

ToolProvidesRelationshipHow many
Inheritance (extends)Implementation + identity"is a kind of"One parent
Interface (implements)A contract, no code"can play the role of"Many
Trait (use)Implementation, no identity"has this capability stamped in"Many

The key distinction: an interface promises behaviour without providing it, a trait provides behaviour without promising anything to the type system (a trait is not a type -- you cannot type-hint against it), and inheritance does both but only once. A frequent, powerful combination is an interface that declares the contract and a trait that supplies a default implementation, so a class implements the interface and uses the trait to get the methods for free while still being recognised by its type.

Composing several traits

A class can stamp in many traits at once, gathering unrelated capabilities into a single type. Here Widget takes both a greeting and a counter, and inside a trait method static::class resolves to the host class.

<?php
declare(strict_types=1);

trait Greets {
    public function hello(): string { return "hello from " . static::class; }
}

trait Counts {
    private int $n = 0;
    public function bump(): void { $this->n++; }
    public function count(): int { return $this->n; }
}

class Widget {
    use Greets, Counts;
}

$w = new Widget();
echo $w->hello(), "\n";
$w->bump();
$w->bump();
echo $w->count(), "\n";

Output:

hello from Widget
2

Widget gains four methods and a property from two independent traits, with no parent involved. Inside Greets::hello, static::class reports Widget -- the host class -- because trait code runs as though written directly in the host, so late static binding resolves to whatever class stamped it in. Two bumps leave the counter at 2. Each trait stays focused on one capability, and the class composes them.

Resolving a method conflict

When two traits offer a method of the same name, PHP forces you to resolve it: insteadof chooses which trait's version wins, and as gives the losing one an alias so it is still reachable.

<?php
declare(strict_types=1);

trait FileLog { public function log(string $m): string { return "[file] $m"; } }
trait DbLog   { public function log(string $m): string { return "[db] $m"; } }

class Service {
    use FileLog, DbLog {
        FileLog::log insteadof DbLog;   // FileLog::log wins the name "log"
        DbLog::log as logToDb;          // DbLog's version kept under a new name
    }
}

$s = new Service();
echo $s->log('started'), "\n";
echo $s->logToDb('started'), "\n";

Output:

[file] started
[db] started

Without the insteadof/as block this class would not even compile -- two log methods collide and PHP refuses to guess. The resolution makes FileLog::log the class's log(), while DbLog's version survives as logToDb(). This explicitness is deliberate: silent resolution would let a newly-added trait quietly hijack an existing method, so PHP makes the choice visible at the use site. It is also a hint that if you are resolving many conflicts, the traits may be doing too much and want splitting.


Real World Example: An Audit Trail Stamped into a Domain Object

Many domain objects need to record what happened to them -- an order, a ticket, a document. Rather than copy that logging into each class or force them all under a common parent, an Auditable trait supplies the machinery, and any class stamps it in. Here an Order uses it to record each state change.

<?php
declare(strict_types=1);

trait Auditable {
    private array $log = [];

    protected function record(string $action): void {
        $this->log[] = $action;
    }

    public function auditTrail(): array {
        return $this->log;
    }
}

class Order {
    use Auditable;

    private string $status = 'new';

    public function __construct(public readonly int $id) {
        $this->record('created');
    }

    public function pay(): void {
        $this->status = 'paid';
        $this->record('paid');
    }

    public function ship(): void {
        $this->status = 'shipped';
        $this->record('shipped');
    }

    public function status(): string {
        return $this->status;
    }
}

$o = new Order(1001);
$o->pay();
$o->ship();

printf("order #%d is %s\n", $o->id, $o->status());
echo "AUDIT TRAIL\n";
echo str_repeat('-', 10), "\n";
foreach ($o->auditTrail() as $i => $action) {
    printf("%d. %s\n", $i + 1, $action);
}

Output:

order #1001 is shipped
AUDIT TRAIL
----------
1. created
2. paid
3. shipped

The Order gets a complete audit mechanism -- the private $log, the protected record() it calls internally, and the public auditTrail() -- from three lines of trait, and a Ticket or Invoice class could gain the identical capability the same way. Each state change records itself, so the trail reads created, paid, shipped in order. The trait keeps its property private so nothing outside can tamper with the log, and exposes only a protected writer, so only the host class can append.

Convenient as it is, this trait carries a real hazard that traits are notorious for: it silently claims the property name $log on every class that uses it. If Order already had its own $log property -- say a shipping log -- stamping in Auditable would collide, and PHP treats a trait-versus-class property conflict as a fatal error only when the definitions differ, otherwise silently merging them, which is arguably worse because two unrelated concerns now share one array. The trait also assumes its host wants an in-memory array that vanishes when the request ends; there is no flushing to storage, so the "audit trail" is lost the moment the object is destroyed. A production design would give the trait a more specific, less collision-prone property name and would define how and when the trail is persisted, rather than leaving it as ephemeral state welded into whatever class happens to stamp it in. The deeper lesson is that a trait's convenience -- code copied straight into the host with full access to $this -- is exactly what makes it risky: it shares the host's namespace and lifetime without the host having asked for anything specific, so a trait's hidden assumptions become the host's silent bugs. Where the shared behaviour genuinely needs its own state and rules, an injected collaborator object states its requirements in its constructor and keeps its state to itself, which is why seasoned code often reaches for composition once a trait grows past a handful of stateless helper methods.


Common Mistakes

  1. Treating a trait as a type. You cannot type-hint a parameter as a trait or check instanceof a trait. If you need a type, pair the trait with an interface; the trait supplies code, the interface supplies the type.
  1. Ignoring method-name conflicts. When two used traits define the same method, the class fails to compile until you resolve it with insteadof and as. Skipping the resolution is a fatal error, not a silent pick.
  1. Letting a trait assume host state. A trait that reads $this->config compiles fine but breaks on any host lacking that property. Traits that depend on host state should declare it themselves or require it through an abstract method.
  1. Colliding property names. A trait's properties are copied into the host, so a trait property that shares a name with a host property can silently merge two unrelated concerns. Give trait properties specific, unlikely-to-clash names.
  1. Overusing traits as a dumping ground. Piling unrelated helpers into one big trait recreates the god-object problem horizontally. Keep each trait focused on a single capability.
  1. Expecting traits to have their own state per trait. A trait's properties live on the host object, not on the trait; two classes using the same trait do not share state, and one object has one copy. Reasoning about the trait as a separate object is wrong.
  1. Putting a constructor in a trait. A trait can define __construct, but if the host or another trait also defines one, they conflict. Prefer an init-style method the host calls, rather than a trait constructor.
  1. Reaching for a trait when composition fits better. If the behaviour is really a collaborator with its own lifecycle, injecting an object is clearer than stamping a trait. Traits are for shared code, not for modelling relationships.
  1. Forgetting that abstract methods in a trait are requirements. A trait may declare an abstract method to force the host to supply it. Overlooking that requirement means the class does not compile until it implements the method.

Best Practices

  • Use a trait for a genuine cross-cutting capability that unrelated classes share, where inheritance would force an artificial common parent.
  • Pair a trait with an interface when callers need a type: the interface names the role, the trait provides the default implementation.
  • Keep each trait small and single-purpose, named for the capability it stamps in (Timestamped, Auditable, Cacheable).
  • Give trait properties distinctive names to avoid silent collisions with host or sibling-trait properties.
  • Declare abstract methods in a trait to state, and have the compiler enforce, what the host must provide.
  • Resolve any method conflict explicitly with insteadof and as, and treat a pile of conflicts as a sign the traits are too broad.
  • Avoid trait constructors; expose an initialiser the host calls, so construction stays under the host's control.
  • Prefer object composition when the behaviour has its own state or lifecycle, reserving traits for stateless-or-simple shared code.

Practice Exercises

  1. Write a Serializable trait with toArray(): array that uses get_object_vars($this), stamp it into two unrelated classes, and show each serialising its own properties.
  1. Create two traits, Slugify and Truncate, each with a format(string $s): string method, and a class that uses both -- resolving the conflict so format is the slug version and the truncate version is available as shorten.
  1. Define a Cacheable trait that requires the host to implement an abstract cacheKey(): string, and a remember method that stores and returns a value keyed by it. Implement a class satisfying the requirement.
  1. Extend the Auditable trait so the trail records a timestamp alongside each action by requiring the host to provide a now(): string method, and demonstrate it on an Invoice class.