PHP enums: backed enums, from() and tryFrom()
An enum (enumeration) declares a type that only accepts a closed list of values: a section of the gazette is FeteDuVillage, Meteo or FaitsDivers (village fair, weather, news in brief), and nothing else. Enums have existed since PHP 8.1.
enum Rubrique: string { case FeteDuVillage = 'village-fair'; case Meteo = 'weather'; case FaitsDivers = 'news-in-brief'; public function libelle(): string { return match ($this) { Rubrique::FeteDuVillage => 'Village fair', Rubrique::Meteo => 'Weather', Rubrique::FaitsDivers => 'News in brief', }; } } $rubrique = Rubrique::from('weather'); // Rubrique::Meteo $inconnue = Rubrique::tryFrom('sports'); // null foreach (Rubrique::cases() as $case) { /* … */ }
With a string, a typo ('wether') goes unnoticed; with an enum, PHP rejects it. A “backed” enum (enum Rubrique: string) gives each case a value, handy for a URL segment or a database column: from() finds the case from its value and throws a ValueError if it doesn't exist, while tryFrom() returns null instead. For a value that comes from the user, like a segment of the address, tryFrom() lets you answer cleanly with a 404 page. An enum can have methods and implement an interface, and a match on its cases doesn't need a default: a forgotten case throws an UnhandledMatchError at runtime, as soon as it is met, instead of slipping through silently.
3 exercises work on this concept, by writing code in the browser.
In the tracks
- Sections Learn PHP 8 from scratch · chapter 2: The newsroom gets organized
- Sections online Learn PHP 8 from scratch · chapter 5: Every article gets its address
- Filtering the menu Symfony for PHP developers · chapter 5: Magic scrolls