Interfaces
An interface is a contract: a list of methods a class promises to provide. It contains no implementation.
<?php
interface Payable
{
public function amountDue(): float;
}
interface Refundable
{
public function refund(): bool;
}
class Order implements Payable, Refundable
{
public function __construct(private float $total) {}
public function amountDue(): float { return $this->total; }
public function refund(): bool { return true; }
}A class can implement many interfaces but extend only one class. That is the main reason interfaces exist.
Code can then depend on the contract rather than a concrete class:
<?php
function charge(Payable $item): void
{
echo "Charging NPR " . $item->amountDue();
}Anything implementing Payable works here — orders, subscriptions,
invoices — without charge() knowing or caring which.
Traits
A trait is a bundle of methods that can be reused by unrelated classes — PHP's answer to "I need this behaviour in two classes that shouldn't share a parent."
<?php
trait Timestampable
{
public ?string $createdAt = null;
public function touch(): void
{
$this->createdAt = date('Y-m-d H:i:s');
}
}
class Article { use Timestampable; }
class Comment { use Timestampable; }
$a = new Article();
$a->touch();
echo $a->createdAt;Multiple traits are fine:
<?php
class Post
{
use Timestampable, SoftDeletes;
}If two traits define the same method, PHP raises an error unless you
resolve it explicitly with insteadof.
Interface vs trait vs abstract class
| Gives you | |
|---|---|
| Interface | a contract, no code, many per class |
| Trait | shared code, no contract, many per class |
| Abstract class | both, but only one per class |
Reach for interfaces by default; use traits for genuinely repeated implementation, and be wary of traits that carry a lot of state.