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
interface PaymentMethodwithfee(float $amount): float.class Cash(fee 0) andclass MobileMoney(fee 2% of the amount), both implementing it.MobileMoney's constructor takes a phone number and throwsInvalidPhoneExceptionunless it is exactly 10 digits.class InvalidPhoneException extends Exception {}.checkout(PaymentMethod $method, float $amount): floatreturns the amount plus the fee.