Topics Object-Oriented PHP Traits & Namespaces
intermediate 12 min read

Traits & Namespaces

Code reuse with traits, conflict resolution, and organizing code with namespaces.

Traits

trait Timestampable {
private DateTime \$createdAt;
private DateTime \$updatedAt;

public function initializeTimestamps(): void {
\$this->createdAt = new DateTime();
\$this->updatedAt = new DateTime();
}
}

class Post {
use Timestampable;
}

Conflict Resolution

trait A { public function foo(): void { echo "A"; } }
trait B { public function foo(): void { echo "B"; } }
class MyClass {
use A, B {
A::foo insteadof B;
B::foo as bar;
}
}

Namespaces

namespace App\Services;

use App\Models\User;
use function array_map;
use const PHP_INT_MAX;

Examples

<?php
trait JsonSerializable {
    public function toJson(): string {
        return json_encode(get_object_vars($this));
    }
}
class Config { use JsonSerializable; public function __construct(private array $data) {} }
echo (new Config(['db'=>'mysql']))->toJson();

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.