← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Enum::cases() & Enum from()/tryFrom()

php PHP 8.1+ Intermediate

TL;DR

Backed enums provide from() (throws on miss) and tryFrom() (returns null) for value lookup, plus cases() to get all cases — essential for forms and validation.

Explanation

UnitEnum::cases() returns an array of all enum cases. BackedEnum::from(string|int) returns the matching case or throws ValueError. BackedEnum::tryFrom() returns null instead of throwing. Use cases() to build select options, from() when the value should always be valid, tryFrom() when handling user input that may be invalid. Pure enums only have cases() — no from()/tryFrom(). PHP 8.3 added typed enum constants.

Common Misconception

from() and tryFrom() work on pure (unit) enums — they only exist on backed enums (those with : string or : int).

Why It Matters

tryFrom() is the idiomatic way to validate enum values from user input — it handles invalid values gracefully without try/catch.

Common Mistakes

  • Using from() on untrusted user input — throws ValueError.
  • Calling tryFrom() on a pure (unit) enum — method doesn't exist.
  • Not using cases() for building form options — manually listing cases duplicates the enum.

Code Examples

✗ Vulnerable
// Unsafe — throws ValueError on invalid input:
$status = Status::from($request->get('status'));

// Building options manually — duplicates enum:
$options = ['active' => 'Active', 'inactive' => 'Inactive'];
✓ Fixed
// Safe user input:
$status = Status::tryFrom($request->get('status')) ?? Status::Active;

// Build options from enum:
$options = array_column(
    array_map(fn(Status $s) => ['value' => $s->value, 'label' => $s->getLabel()], Status::cases()),
    'label', 'value'
);

Added 22 Mar 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 1 ping F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S
No pings yesterday
Amazonbot 8 Unknown AI 4 Google 3 Perplexity 3 SEMrush 2 ChatGPT 1 Ahrefs 1
crawler 18 crawler_json 2 pre-tracking 2
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Use tryFrom() for user input (never from()). Use cases() to build form options. Use from() only when values are from a trusted internal source.
📦 Applies To
PHP 8.1+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
::from\(
Auto-detectable: ✓ Yes phpstan psalm
⚠ Related Problems
🤖 AI Agent
Confidence: High False Positives: Medium ✓ Auto-fixable Fix: Low Context: Line Tests: Update
CWE-20

✓ schema.org compliant