php · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A duck and a penguin. Which can fly?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
interface Flies {}
interface Swims {}
class Duck implements Flies, Swims {}
class Penguin implements Swims {}
$birds = ["duck" => new Duck(), "penguin" => new Penguin()];
foreach ($birds as $name => $bird) {
if ($bird instanceof Flies) {
echo "The $name can fly.\n";
} else {
echo "The $name stays on the ground.\n";
}
}
your turn
Your turn. Invent a new deal for the till.
Name a new discount class in both name blanks, like FiverOff, and type how many pounds it takes off. The till takes any class that keeps the Discount promise.
fix it
This logger looks right, but PHP refuses it. Fix it.
- The
TypeErrorsayssave()wants aLogger, but got aScreenLogger. DoesScreenLoggersay it is one? - Having the right method is not enough. PHP only trusts classes that sign the promise by name.
- On line 5, add
implements Loggerafterclass ScreenLogger, then run it.
nailed it
your classes keep their promises. :D
- An interface lists methods, and
implementspromises to write them. - Use an interface as a type to accept any class keeping it.
instanceofchecks whether an object keeps a promise.
new words in your collection
- interface
- implements
- polymorphism
This lesson isn’t saved. A free account remembers every lesson you finish.