← Home ← Codex ← DEBT ← Engine
Browse by Category
+ added · updated 7d
← Back to glossary

Enums (PHP 8.1)

PHP PHP 8.1+ Intermediate
debt(d5/e3/b3/t5)
d5 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches it' (d5). The detection_hints list rector, phpstan, and psalm — all specialist static analysis tools. Common misuse patterns (using const clusters instead of enums, from() without error handling, == vs === comparisons) are not caught by default linters but are detectable by phpstan/psalm with appropriate rule sets.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). The quick_fix describes replacing string/int constants with a backed enum — a straightforward pattern replacement within one component. Individual mistakes like from() vs tryFrom() or == vs === are one-line fixes (e1), but migrating a full set of related constants to an enum touches multiple call sites within a component, landing closer to e3.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3). Enums apply to web, cli, and queue-worker contexts but their scope is per-type-definition. Once defined, an enum imposes minimal ongoing burden — it actually reduces future maintenance cost by providing type safety. The debt is localised to teams unfamiliar with enum semantics rather than being a system-wide structural weight.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The misconception field identifies a documented gotcha: developers familiar with class constants assume enums are just grouped constants, missing that they are proper types. The from() vs tryFrom() trap and == vs === comparison issues are well-documented surprises that most PHP developers encounter. Not a contradiction with another language's concept (which would be t7), but a notable documented gotcha warranting t5.

About DEBT scoring →

Also Known As

PHP enums PHP 8.1 enums backed enum pure enum

TL;DR

Native enumerations providing type-safe named constants that replace class-constant patterns and stringly-typed values.

Explanation

PHP 8.1 enums come in two flavours: pure enums (no backing value) and backed enums (int or string backed). Backed enums support from() and tryFrom() for creating instances from raw values. Enums can implement interfaces, have methods and constants, and be used in type declarations. They eliminate the bugs associated with stringly-typed states, magic numbers, and inconsistent constant naming, and provide exhaustiveness checking in match expressions.

Common Misconception

PHP enums are equivalent to class constants grouped in a class. Enums are proper types — they can implement interfaces, have methods, be used as type hints, and cannot be instantiated arbitrarily. A function typed to accept Suit only accepts valid Suit cases, not any string.

Why It Matters

PHP 8.1 native enums replace string/integer constants with type-safe, exhaustively checkable cases — match expressions on enums produce a compile-time error for unhandled cases.

Common Mistakes

  • Using backed enum values (string/int) when a pure enum would be cleaner — backed values are for serialization.
  • Not implementing interfaces on enums when shared behaviour is needed — enums can implement interfaces.
  • Using from() without handling the ValueError it throws for invalid values — use tryFrom() for user input.
  • Comparing enum cases with == instead of === — always use strict comparison or match.

Code Examples

✗ Vulnerable
// Old-style string constants — no type safety or exhaustiveness:
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
function process(string $status): void { /* $status can be any string */ }

// PHP 8.1 enum:
enum Status { case Active; case Inactive; }
function process(Status $status): void { /* only valid cases accepted */ }
✓ Fixed
// Pure enum (no backing value)
enum Status { case Pending; case Paid; case Shipped; case Cancelled; }

// Backed enum — maps to string or int stored in DB
enum OrderStatus: string {
    case Pending   = 'pending';
    case Paid      = 'paid';
    case Shipped   = 'shipped';

    // Enums can have methods
    public function label(): string {
        return match($this) {
            self::Pending  => 'Awaiting payment',
            self::Paid     => 'Processing',
            self::Shipped  => 'On the way',
        };
    }
}

$status = OrderStatus::from('paid');       // OrderStatus::Paid
$status = OrderStatus::tryFrom('unknown'); // null (no exception)
echo $status->label();                     // 'Processing'

Added 15 Mar 2026
Edited 22 Mar 2026
Views 83
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 1 ping S 0 pings M 1 ping T 0 pings W 1 ping T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 2 pings T 0 pings F 0 pings S 1 ping S 0 pings M 1 ping T 0 pings W
No pings yet today
Google 1
Scrapy 17 Ahrefs 9 Amazonbot 9 Perplexity 7 Google 6 SEMrush 6 Unknown AI 3 ChatGPT 3 Majestic 2 PetalBot 2 Meta AI 1 Twitter/X 1 Applebot 1
crawler 61 crawler_json 5 pre-tracking 1
🧱 FUNDAMENTALS — new to this? Start with the ground floor.
PHP php A server-side scripting language that generates web pages and APIs — the code runs on the server, and only its output (usually HTML or JSON) reaches the browser.

PHP is often the first server-side language people meet, and understanding its execution model — script starts fresh on every request, no memory between requests — explains most of how the web backend works: sessions, databases, and caching all exist to bridge that per-request amnesia.

💡 Start with PHP 8.x, declare(strict_types=1), and PDO — skip any tutorial that mentions mysql_query().

Ask Codex about PHP →
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Medium
⚡ Quick Fix
Replace string/int constants (const STATUS_ACTIVE = 'active') with a backed enum — it adds type safety, IDE support, and methods
📦 Applies To
PHP 8.1+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
Class or interface with multiple related const string/int definitions used as status/type values
Auto-detectable: ✓ Yes rector phpstan psalm
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Low Context: File


✓ schema.org compliant