Lessons → PHP OOP → Lesson 5

Traits

PHP
⏱ 15 min read📖 IntermediateNot completed

Traits are a mechanism for code reuse in PHP. They allow you to include methods in multiple classes without using inheritance.

Basic Trait

PHP
<?php
trait Timestamps {
    public function createdAt(): string {
        return date("Y-m-d H:i:s");
    }

    public function updatedAt(): string {
        return date("Y-m-d H:i:s");
    }
}

trait SoftDeletes {
    private bool $deleted = false;

    public function delete(): void {
        $this->deleted = true;
    }

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

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

class User {
    use Timestamps, SoftDeletes;  // Use multiple traits!

    public function __construct(public string $name) {}
}

class Post {
    use Timestamps, SoftDeletes;

    public function __construct(public string $title) {}
}

$user = new User("John");
echo $user->createdAt();   // 2025-05-22 10:00:00
$user->delete();
echo $user->isDeleted();   // true

$post = new Post("My Article");
echo $post->createdAt();   // same trait, different class
?>

Traits vs Inheritance vs Interfaces

TraitInheritanceInterface
Code reuseYesYesNo
Multiple useYesNoYes
Has method bodiesYesYesNo
Creates "is-a" relationNoYesYes

Trait with Abstract Method

PHP
<?php
trait Validatable {
    abstract protected function rules(): array;

    public function validate(array $data): bool {
        foreach ($this->rules() as $field => $rule) {
            if ($rule === 'required' && empty($data[$field])) {
                echo "Field '$field' is required\n";
                return false;
            }
        }
        return true;
    }
}

class LoginForm {
    use Validatable;

    protected function rules(): array {
        return [
            'email'    => 'required',
            'password' => 'required',
        ];
    }
}

$form = new LoginForm();
$form->validate(['email' => '', 'password' => '123']);
// Field 'email' is required
?>
💡
Laravel uses traits heavily! Eloquent models use HasFactory, SoftDeletes, HasApiTokens traits. You'll see use HasFactory, SoftDeletes; in almost every model.
🎉
PHP OOP complete! You now know classes, constructors, inheritance, interfaces, and traits. You're ready for Laravel! Head to the Laravel lessons next.
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take a quiz to reinforce what you learned.

Take Quiz →