Docs/PHP/Interfaces & Traits

Interfaces & Traits

Interface

Kontrak yang harus diimplementasi oleh class. Hanya deklarasi method, tanpa implementasi.

Trait

Code reuse mechanism — seperti "copy-paste" method ke dalam class. PHP tidak support multiple inheritance, tapi bisa pakai banyak traits.

index.php
Try It →
<?php
interface Printable {
    public function toString(): string;
}

interface Saveable {
    public function save(): bool;
}

trait Timestampable {
    public string $createdAt;
    public function setTimestamp(): void {
        $this->createdAt = date("Y-m-d H:i:s");
    }
}

trait Sluggable {
    public function makeSlug(string $text): string {
        return strtolower(str_replace(" ", "-", $text));
    }
}

class Article implements Printable, Saveable {
    use Timestampable, Sluggable;
    
    public function __construct(public string $title) {
        $this->setTimestamp();
    }
    
    public function toString(): string {
        return "[{$this->createdAt}] {$this->title}";
    }
    
    public function save(): bool { return true; }
}

$article = new Article("Belajar PHP OOP");
echo $article->toString() . "
";
echo "Slug: " . $article->makeSlug($article->title) . "
";
echo "Saved: " . ($article->save() ? "Yes" : "No");
?>