Interfaces define a contract of methods that a class must implement. A class can implement multiple interfaces using the implements keyword. This keeps code flexible and ensures consistency across different implementations.
Interfaces
// Define interface — contract, no implementation
interface Payable {
public function pay(float $amount): bool;
public function refund(float $amount): bool;
}
interface Notifiable {
public function notify(string $message): void;
}
// Implement multiple interfaces
class Order implements Payable, Notifiable {
public function pay(float $amount): bool {
// process payment
return true;
}
public function refund(float $amount): bool {
// process refund
return true;
}
public function notify(string $message): void {
mail("user@example.com", "Order Update", $message);
}
}
// Type hint by interface
function checkout(Payable $item): void {
$item->pay(100.00);
}