What is it?
An interface is a contract — it says every class that implements it MUST have certain methods. A trait is a reusable code block that any class can include regardless of its inheritance.
Why does it matter?
Interfaces enable polymorphism — you can write functions that accept any Printable, any Loggable, any Exportable. Traits prevent copy-pasting the same methods (like log() or timestamps) across dozens of unrelated classes.
Learn PHP interfaces and traits — contracts, code reuse, multiple interfaces.
Real-World Use Cases
- 📨 Notification system - A Notifiable interface ensures every notification type has a send() method. SMS, Email, and Push classes all implement it interchangeably.
- 📝 Audit trail - A Loggable trait adds a log() method to Order, User, and Product classes — no duplication, no inheritance needed.
- 📤 Data export - An Exportable interface requires exportToCsv() and exportToJson() — any report class can implement it.
- ⏱️ Timestamps - A Timestampable trait adds setCreatedAt() and setUpdatedAt() to every model without a shared parent.
Interface — a Contract
<?php
interface Document
{
public function print(): void;
public function getTitle(): string;
}
class Invoice implements Document
{
private int $number;
public function __construct(int $number)
{
$this->number = $number;
}
public function print(): void
{
echo "Printing invoice #{$this->number}" . PHP_EOL;
}
public function getTitle(): string
{
return "Invoice #{$this->number}";
}
}
$invoice = new Invoice(101);
$invoice->print();
echo $invoice->getTitle();
Trait — Reusable Code Block
<?php
trait Logger
{
public function log(string $message): void
{
echo date('Y-m-d H:i:s') . " | " . $message . PHP_EOL;
}
}
class Order
{
use Logger;
public function place(): void
{
$this->log('Order placed successfully');
}
}
(new Order())->place();
Multiple Interfaces on One Class
<?php
interface Printable
{
public function print(): void;
}
interface Exportable
{
public function export(): void;
}
class Report implements Printable, Exportable
{
public function print(): void
{
echo "Printing report..." . PHP_EOL;
}
public function export(): void
{
echo "Exporting report..." . PHP_EOL;
}
}
$report = new Report();
$report->print();
$report->export();
Q: What is the difference between an interface and a trait?
An interface is a pure contract — defines WHAT methods a class must have, no code. A trait provides actual reusable code. Use interfaces for type-checking. Use traits to avoid duplicating methods across unrelated classes.
Comments (0)
No comments yet. Be the first!
Leave a Comment