Enum::cases() & Enum from()/tryFrom()
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'
);
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Views
23
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
No pings yesterday
Amazonbot 8
Unknown AI 4
Google 3
Perplexity 3
SEMrush 2
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 18
crawler_json 2
pre-tracking 2
Related categories
⚡
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