php · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An is a type with a fixed menu of values.
Traffic lights are red, amber or green, never purple. A string cannot promise that, because "gren" is a string too. An enum lists every possible value as an , and nothing else ever exists. Light::Green is real. A typo is an error.
Use the enum as a type and a function can only receive one of its cases. Compare cases with ===, and get them all, in order, with Light::cases(). Each case also knows its own name through ->name.
<?php
enum Light {
case Red;
case Amber;
case Green;
}
function canGo(Light $light): bool {
return $light === Light::Green;
}
foreach (Light::cases() as $light) {
if (canGo($light)) {
echo "$light->name: go\n";
} else {
echo "$light->name: wait\n";
}
} Each case exists only once, so === is the right way to compare two of them.
guess first
Two coffee orders. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
enum Size {
case Small;
case Large;
}
function cup(Size $size): string {
return "One $size->name coffee";
}
echo cup(Size::Large) . "\n";
echo cup("Small") . "\n";
your turn
Your turn. Finish the planet list.
Type the name of the third planet from the Sun as a new case, with a capital letter, then run it to number every case.
fix it
The customer paid, but nobody believes them. Fix it.
- No error this time, only the wrong answer. Look at what line 7 compares
$paymentwith. $paymentholds an enum case, and an enum case is never===to a string, even one spelt the same.- On line 7, change
"Paid"toPayment::Paid, then run it.
nailed it
your types have a fixed menu now. :D
- An enum lists every possible value as a named case.
- Use an enum as a type so only real cases get in.
- Compare cases with
===and list them withcases().
new words in your collection
- enum
- enum case
This lesson isn’t saved. A free account remembers every lesson you finish.