Lesson 8 of 8 · 12 min

Interfaces, inheritance and exceptions

Interfaces

An interface lists methods a class promises to have, without saying how they work:

interface Notifier
{
    public function send(string $message): bool;
}

class SmsNotifier implements Notifier
{
    public function send(string $message): bool { /* ... */ return true; }
}

Code that accepts a Notifier works with any class that implements it, today's and tomorrow's:

function alert(Notifier $n): void { $n->send("Server is down"); }

Inheritance and abstract classes

extends reuses a parent class. An abstract class cannot be created directly; it exists to share code and to require children to fill in abstract methods.

abstract class Shape
{
    abstract public function area(): float;
    public function describe(): string { return static::class . " of area " . $this->area(); }
}

Your own exceptions

Make a class that extends Exception for each kind of problem your code can report. Callers can then catch exactly the problems they know how to handle:

class OutOfStockException extends Exception {}

try {
    $shop->sell("Soap", 5);
} catch (OutOfStockException $e) {
    echo "Sorry: " . $e->getMessage();
}

preg_match('/^\d{10}$/', $phone) is true when $phone is exactly 10 digits.

Your task

  1. interface PaymentMethod with fee(float $amount): float.
  2. class Cash (fee 0) and class MobileMoney (fee 2% of the amount), both implementing it. MobileMoney's constructor takes a phone number and throws InvalidPhoneException unless it is exactly 10 digits.
  3. class InvalidPhoneException extends Exception {}.
  4. checkout(PaymentMethod $method, float $amount): float returns the amount plus the fee.
index.php
<?php
// interface PaymentMethod ...

// class InvalidPhoneException ...

// class Cash ...

// class MobileMoney ...

// function checkout(...)

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…