Interface mendefinisikan kontrak — method apa yang harus diimplementasikan. Trait berbagi implementasi antar class.
Interface:
interface Printable {
public function toString(): string;
}
interface Loggable {
public function log(): void;
}
class Invoice implements Printable, Loggable {
public function toString(): string { return "Invoice #" . $this->id; }
public function log(): void { logger()->info($this->toString()); }
}
Trait — code reuse tanpa inheritance:
trait HasTimestamps {
public function getCreatedAt(): string {
return $this->created_at->format("d M Y");
}
public function isRecent(): bool {
return $this->created_at->isAfter(now()->subDays(7));
}
}
class Post extends Model {
use HasTimestamps; // Sekarang Post punya getCreatedAt() dan isRecent()
}
class Comment extends Model {
use HasTimestamps; // Comment juga!
}
Kapan pakai apa?
- Interface: mendefinisikan APA yang harus bisa dilakukan
- Trait: berbagi BAGAIMANA melakukannya
- Abstract class: keduanya + shared state