×

php · level 3 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a promise: any class that signs it has these methods.

A plug fits any socket, whoever made the kettle. An interface works the same way. It lists methods with no code at all. A class that it promises to write every one of them, and PHP checks.

The interface's name then works as a type. A function asking for a Notifier accepts an email notifier, a text notifier, or one nobody has written yet. Using many kinds of object through one shared promise is called .

A class extends only one parent, but can implement many interfaces. Check for one with instanceof.

<?php
interface Notifier {
    public function send(string $message): string;
}
class EmailNotifier implements Notifier {
    public function send(string $message): string { return "Email: $message"; }
}
class TextNotifier implements Notifier {
    public function send(string $message): string { return "Text: $message"; }
}
function alert(Notifier $notifier): void {
    echo $notifier->send("Your parcel has arrived") . "\n";
}
alert(new EmailNotifier());
alert(new TextNotifier());

alert() never asks which kind of notifier it has, because the promise is all it needs.