Skip to content
Traits
step 1/6

Reading — step 1 of 6

Learn

~1 min readReuse Patterns

PHP doesn't support multiple inheritance. Traits fill the gap — a trait is a reusable bundle of methods that a class can use.

trait Loggable {
    public function log(string $msg): void {
        echo "[" . static::class . "] $msg\n";
    }
}

trait Timestampable {
    public ?\DateTimeImmutable $createdAt = null;
    public function touch(): void {
        $this->createdAt = new \DateTimeImmutable();
    }
}

class User {
    use Loggable, Timestampable;
    public function __construct(public string $name) {}
}

$u = new User('Ada');
$u->log('created');     // [User] created
$u->touch();

Conflict resolution when two traits define the same method:

class C {
    use A, B {
        A::greet insteadof B;     // use A's, alias B's
        B::greet as greetFromB;
    }
}

When traits vs interfaces vs abstract classes:

  • Interface — declare a contract, no implementation
  • Abstract class — partial implementation + can hold state, single inheritance
  • Trait — code reuse without inheritance, can have state, multiple uses

Trait methods become part of the class — they're flattened in, not delegated. They can call methods on $this that the using class provides.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…