Content · Web Development · PHP

Using Enums to Model States

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.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

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


ApproachDifference
Using Enums to Model StatesEnums represent a closed set of valid states instead of unvalidated strings.
Related API or alternativeFree-form strings can contain invalid states; enum cases cannot.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the operation-specific limitsBacked enums provide from/tryFrom for external scalar data, but adding a new case still requires consumers to handle it.
Confusing it with a related APIFree-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.

Share this resourceSend this page to someone who may find it useful.