Skip to main content

Lesson 2 of 7

Traits - Horizontal Code Reuse

Traits solve a specific problem: PHP only supports single inheritance, so if two unrelated classes need the same method, you can't share it via a parent class. Traits let you extract reusable method groups and compose them into any class - like mixins in other languages.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Traits - Composition over Inheritance

Traits - Composition over Inheritance
<?php
declare(strict_types=1);

// ── Timestamp trait - used by Post, User, Comment, Product... ──
trait HasTimestamps {
    public readonly DateTimeImmutable $createdAt;
    public ?DateTimeImmutable         $updatedAt = null;

    private function initTimestamps(): void {
        $this->createdAt = new DateTimeImmutable("now", new DateTimeZone("UTC"));
    }

    public function touch(): void {
        $this->updatedAt = new DateTimeImmutable("now", new DateTimeZone("UTC"));
    }

    public function getAge(): string {
        $diff = $this->createdAt->diff(new DateTimeImmutable());
        return match(true) {
            $diff->d === 0  => "Today",
            $diff->d === 1  => "Yesterday",
            $diff->d < 7   => "{$diff->d} days ago",
            default         => $this->createdAt->format("M j, Y"),
        };
    }
}

// ── SoftDelete trait - logical delete without removing the row ──
trait SoftDeletes {
    private bool               $deleted   = false;
    private ?DateTimeImmutable $deletedAt = null;

    public function softDelete(): void {
        $this->deleted   = true;
        $this->deletedAt = new DateTimeImmutable();
    }

    public function restore(): void {
        $this->deleted   = false;
        $this->deletedAt = null;
    }

    public function isDeleted(): bool { return $this->deleted; }
    public function getDeletedAt(): ?DateTimeImmutable { return $this->deletedAt; }
}

// ── Validation trait - used by form request classes ──────────
trait Validatable {
    private array $errors = [];

    abstract protected function rules(): array;

    public function validate(array $data): bool {
        $this->errors = [];
        foreach ($this->rules() as $field => $rule) {
            if (str_contains($rule, "required") && empty($data[$field])) {
                $this->errors[$field] = ucfirst($field) . " is required.";
            }
        }
        return empty($this->errors);
    }

    public function getErrors(): array  { return $this->errors; }
    public function hasErrors(): bool   { return !empty($this->errors); }
}

// ── Using multiple traits ──────────────────────────────────────
class Post {
    use HasTimestamps, SoftDeletes;

    public function __construct(
        public readonly string $title,
        public readonly string $slug,
    ) {
        $this->initTimestamps();
    }
}

class User {
    use HasTimestamps, SoftDeletes;

    public function __construct(
        public readonly string $email,
    ) {
        $this->initTimestamps();
    }
}

// ── Trait conflict resolution ──────────────────────────────────
trait A { public function hello(): string { return "A"; } }
trait B { public function hello(): string { return "B"; } }

class MyClass {
    use A, B {
        A::hello insteadof B;   // use A's version
        B::hello as helloB;     // but also keep B's as helloB()
    }
}

$obj = new MyClass();
echo $obj->hello();   // "A"
echo $obj->helloB();  // "B"

Quick Quiz

Tip

Tip

Practice Traits Horizontal Code Reuse in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Traits - Horizontal Code Reuse

Practice Task

Note

Practice Task - (1) Write a working example of Traits Horizontal Code Reuse from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Traits Horizontal Code Reuse is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done