iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Interfaces

An interface is a contract — a list of methods a class promises to implement. Interfaces give you polymorphism without inheritance.

Defining one

PHP
interface Payable {
    public function total(): float;
    public function description(): string;
}

Implementing it

PHP
class Invoice implements Payable {
    public function __construct(private float $amount, private string $for) {}

    public function total(): float        { return $this->amount * 1.10; }   // +10% tax
    public function description(): string { return $this->for; }
}

class Subscription implements Payable {
    public function __construct(private float $monthly, private int $months) {}

    public function total(): float        { return $this->monthly * $this->months; }
    public function description(): string { return "{$this->months}-month subscription"; }
}

Use the interface as a type

PHP
function process(Payable $p): void {
    echo $p->description(), ': $', number_format($p->total(), 2);
}

process(new Invoice(100, 'Hosting'));
process(new Subscription(9.99, 12));

A class can implement many

PHP
interface Countable { public function count(): int; }
interface JsonSerializable { public function jsonSerialize(): mixed; }

class Cart implements Countable, JsonSerializable {
    public function count(): int { ... }
    public function jsonSerialize(): mixed { ... }
}

Interface constants

PHP
interface Status {
    const PAID     = 'paid';
    const PENDING  = 'pending';
    const REFUNDED = 'refunded';
}

echo Status::PAID;
Tip: Program against interfaces, not classes. function send(Logger $log) with Logger as an interface lets you swap the file-logger for a stub in tests.

Example

Example
<?php
interface Payable {
    public function total(): float;
}
class Invoice implements Payable {
    public function __construct(private float $amount) {}
    public function total(): float { return $this->amount * 1.10; }
}
echo (new Invoice(100))->total();
Try it Yourself »

Exercise

Promise to provide methods with…

class Invoice Payable {}

Test yourself

Q1. A class can implement…
Q2. Interface methods have…
Q3. Programming against interfaces makes code…

Discussion

Loading…