Enums represent a closed set of valid states instead of unvalidated strings.
The examples focus on the operation itself, including the important distinction: Free-form strings can contain invalid states; enum cases cannot.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Before You Start
Read the input requirements before applying this pattern to production data.
Example 1: Basic Use
tryFrom returns null on unknown input, unlike from which throws ValueError.
<?php
enum TicketState: string { case New = "new"; case Ready = "ready"; case Done = "done"; }
$state = TicketState::tryFrom('new');
echo $state?->name ?? "invalid state";
Output from a successful local PHP 8.4 run:
New
Example 2: Checking Behavior
tryFrom returns null on unknown input, unlike from which throws ValueError.
<?php
enum TicketState: string { case New = "new"; case Ready = "ready"; case Done = "done"; }
$state = TicketState::tryFrom('ready');
echo $state?->name ?? "invalid state";
Output from a successful local PHP 8.4 run:
Ready
Example 3: Practical Example
tryFrom returns null on unknown input, unlike from which throws ValueError.
<?php
enum TicketState: string { case New = "new"; case Ready = "ready"; case Done = "done"; }
$state = TicketState::tryFrom('done');
echo $state?->name ?? "invalid state";
Output from a successful local PHP 8.4 run:
Done
Important Behavior and Edge Cases
Backed enums provide from/tryFrom for external scalar data, but adding a new case still requires consumers to handle it.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| Using Enums to Model States | Enums represent a closed set of valid states instead of unvalidated strings. |
| Related API or alternative | Free-form strings can contain invalid states; enum cases cannot. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Backed enums provide from/tryFrom for external scalar data, but adding a new case still requires consumers to handle it. |
| Confusing it with a related API | Free-form strings can contain invalid states; enum cases cannot. |
Key Takeaways
- Enums represent a closed set of valid states instead of unvalidated strings.
- Backed enums provide from/tryFrom for external scalar data, but adding a new case still requires consumers to handle it.
- Free-form strings can contain invalid states; enum cases cannot.
Use Using Enums to Model States when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.