php · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A gives every case a value you can save.
Databases and forms speak in strings, not enum cases. A backed enum gives each case a fixed value: enum Status: string, with case Shipped = "shipped";. Read it with ->value when you save, and turn it back into a case with Status::from("shipped") when you load.
If no case matches, from() throws a . For input you do not trust, tryFrom() returns null instead, and a type written ?Status means a Status or null. Enums can hold methods too, where $this is the current case.
<?php
enum Status: string {
case Pending = "pending";
case Shipped = "shipped";
public function label(): string {
return "Order is $this->value";
}
}
$saved = Status::Shipped->value;
echo "Saved as: $saved\n";
$loaded = Status::from($saved);
echo $loaded->label() . "\n";
$unknown = Status::tryFrom("lost");
echo gettype($unknown) . "\n"; ->name is the case's name in your code, and ->value is what you store.
guess first
A form asks for size XL. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
enum Size: string {
case Small = "S";
case Medium = "M";
case Large = "L";
}
$fromForm = "XL";
$size = Size::from($fromForm);
echo "You picked $size->name\n";
your turn
Your turn. Let a visitor pick a theme.
Line 6 pretends a visitor asked for a theme in the link. Type any theme, real or made up. Unknown ones fall back to light, because ?? picks its right side when the left is null.
fix it
A made-up plan crashes the sign-up page. Fix it.
- The first plan works. The
ValueErrorcomes from line 7 on the second call. Why does??not catch it? ??only steps in when the left side isnull.from()never returnsnull: it throws first.- On line 7, change
Plan::fromtoPlan::tryFrom, then run it.
nailed it
your enums can be saved and loaded. :D
- A backed enum gives each case a fixed string or integer.
from()throws aValueError, whiletryFrom()returnsnull.- Enums can have methods, with
$thisas the current case.
new words in your collection
- backed enum
- ValueError
This lesson isn’t saved. A free account remembers every lesson you finish.