Magic Strings
Also Known As
magic string
hardcoded string literal
unnamed string constant
TL;DR
Raw string literals used directly in code as identifiers or flags — prone to typos, hard to refactor, and lacking IDE support.
Explanation
Magic strings are the string equivalent of magic numbers: inline string literals like 'admin', 'pending', or 'user_created' used as status values, event names, or configuration keys. They cause typo bugs that aren't caught until runtime, resist refactoring (no IDE rename support), and offer no context to readers. Replace them with constants, enums (PHP 8.1+), or class constants — these are findable, renameable, and document valid values in one place.
Common Misconception
✗ Magic strings are only a problem when the same string appears in multiple places. A single unexplained string like "pending" in a status check is still a magic string — a named constant Status::PENDING is refactoring-safe, self-documenting, and IDE-navigable.
Why It Matters
Magic strings are literal string values used directly in code without explanation or central definition — a typo in one copy goes undetected because there is no single source of truth to validate against.
Common Mistakes
- Status values as strings scattered across the codebase: 'active', 'pending', 'inactive' — define as constants or enums.
- Event names as raw strings: event('user.created') — a typo in the listener silently misses the event.
- Config keys as inline strings repeated everywhere — one rename requires searching the whole codebase.
- Error message strings duplicated in multiple places — they diverge and give users inconsistent messages.
Code Examples
✗ Vulnerable
if ($user->role === 'admin') { /* typo risk */ }
✓ Fixed
if ($user->role === Role::ADMIN->value) { /* enum backed by string */ }
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
33
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 15
Perplexity 6
Ahrefs 4
Unknown AI 3
Google 2
Majestic 1
Also referenced
How they use it
crawler 29
crawler_json 1
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Replace string literals used as status codes, types, or identifiers with PHP 8.1 enums or class constants — they're refactoring-safe and PHPStan can verify exhaustiveness
📦 Applies To
any
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
if ($status === 'active') or match($type) on string literals; same string literal repeated in multiple files
Auto-detectable:
✓ Yes
phpmd
phpcs
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: File