Interfaces & Abstract Classes
PHPInterfaces and abstract classes define contracts that other classes must follow. They're key to writing flexible, maintainable code.
Interfaces
An interface defines what methods a class must have, without implementing them:
PHP
<?php
interface Payable {
public function pay(float $amount): bool;
public function getBalance(): float;
}
interface Notifiable {
public function notify(string $message): void;
}
// Class must implement ALL interface methods
class CreditCard implements Payable, Notifiable {
private float $balance = 5000;
public function pay(float $amount): bool {
if ($amount > $this->balance) return false;
$this->balance -= $amount;
return true;
}
public function getBalance(): float {
return $this->balance;
}
public function notify(string $message): void {
echo "SMS: $message\n";
}
}
$card = new CreditCard();
$card->pay(100);
echo $card->getBalance(); // 4900
$card->notify("Payment of ¥100 received");
?>Abstract Classes
Abstract classes can have both abstract methods (no body) and concrete methods (with body):
PHP
<?php
abstract class Report {
// Abstract method — child MUST implement this
abstract protected function getData(): array;
// Concrete method — shared by all children
public function generate(): void {
$data = $this->getData();
echo "<h1>" . $this->getTitle() . "</h1>\n";
foreach ($data as $row) {
echo "- $row\n";
}
}
abstract protected function getTitle(): string;
}
class SalesReport extends Report {
protected function getData(): array {
return ["Jan: ¥100,000", "Feb: ¥120,000", "Mar: ¥95,000"];
}
protected function getTitle(): string {
return "Monthly Sales Report";
}
}
$report = new SalesReport();
$report->generate();
// <h1>Monthly Sales Report</h1>
// - Jan: ¥100,000
// - Feb: ¥120,000
// - Mar: ¥95,000
?>Interface vs Abstract Class
| Interface | Abstract Class | |
|---|---|---|
| Can have method bodies | No (PHP 8: default methods) | Yes |
| Can have properties | Constants only | Yes |
| Multiple inheritance | Yes (implement many) | No (extend one) |
| Constructor | No | Yes |
| Use when | Defining a contract | Sharing base behavior |
💡
Laravel uses interfaces extensively!
Illuminate\Contracts\Auth\Guard, Illuminate\Contracts\Cache\Repository — these are interfaces. This is why you can swap implementations easily in Laravel.Test your knowledge!
Take a quiz to reinforce what you learned.