Interfaces
An interface defines a contract of methods a class must implement.
Syntax
interface Name {
public function method();
}
class C implements Name { ... }An interface lists method signatures without any code. A class that implements an interface promises to provide those methods.
Interfaces let unrelated classes share a common contract, which is a form of polymorphism.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Define a PaymentGateway interface so Stripe and PayPal adapters can be swapped without changing the checkout code.
- Use a Logger interface to allow different logging backends (file, database, Slack) in a dependency-injected service.
- Implement a Serializable interface on data transfer objects to enforce a consistent toArray() contract.
More examples
Defining and implementing an interface
An interface defines method signatures without implementation; implementing classes must provide every declared method.
<?php
interface PaymentGateway {
public function charge(float $amount, string $currency): bool;
public function refund(string $transactionId): bool;
}
class StripeGateway implements PaymentGateway {
public function charge(float $amount, string $currency): bool {
// call Stripe API
return true;
}
public function refund(string $transactionId): bool {
// call Stripe refund API
return true;
}
}Type-hinting against an interface
Type-hinting against Logger lets processOrder work with any logger implementation, decoupling it from storage details.
<?php
interface Logger {
public function log(string $message): void;
}
class FileLogger implements Logger {
public function log(string $message): void {
file_put_contents('/tmp/app.log', $message . "\n", FILE_APPEND);
}
}
function processOrder(array $order, Logger $logger): void {
$logger->log("Order {$order['id']} processed");
}
processOrder(['id' => 99], new FileLogger());Implementing multiple interfaces
A class can implement multiple interfaces, satisfying several independent contracts simultaneously.
<?php
interface Printable {
public function print(): void;
}
interface Exportable {
public function toJson(): string;
}
class Report implements Printable, Exportable {
public function __construct(private string $title) {}
public function print(): void {
echo $this->title;
}
public function toJson(): string {
return json_encode(['title' => $this->title]);
}
}
$r = new Report('Q1 Results');
$r->print();
echo $r->toJson();
Discussion