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

Replace Magic Literal with Symbolic Constant

quality Beginner

TL;DR

Magic literals (numbers/strings hardcoded without context) should become named constants — MAX_RETRIES = 3 is self-documenting; the literal 3 is not.

Explanation

Magic literals are unexplained values scattered through code. Types: magic numbers (if ($score > 42)), magic strings (if ($status === 'pnd')). Replace with: class constants (public const MAX_SCORE = 100), enums (Status::Pending), named constants (define('MAX_RETRIES', 3)), or config values. Benefits: single definition, searchable, self-documenting, single point to change. PHP: prefer class constants over global constants for scoping. Only exception: 0, 1, -1, true, false, empty string — universally understood.

Common Misconception

Any named constant is better than a literal — constants for truly obvious values (0, 1, true) add noise without clarity.

Why It Matters

Magic literals make code impossible to understand without external documentation and create bugs when the same value is hardcoded in multiple places and one is missed during a change.

Common Mistakes

  • Using string literals for status values — use enums or class constants.
  • Duplicating the same magic number in 10 places — one constant, 10 references.
  • Creating constants with useless names: CONST_42 = 42.

Code Examples

✗ Vulnerable
if ($attempts > 3) { sleep(30); } // What are 3 and 30?
if ($status === 'pnd') { } // What is 'pnd'?
✓ Fixed
const MAX_RETRY_ATTEMPTS = 3;
const RETRY_DELAY_SECONDS = 30;

if ($attempts > MAX_RETRY_ATTEMPTS) { sleep(RETRY_DELAY_SECONDS); }

enum OrderStatus: string {
    case Pending = 'pending';
    case Complete = 'complete';
}

Added 23 Mar 2026
Views 23
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 1 ping T 0 pings F 0 pings S 2 pings S 0 pings M 0 pings T 0 pings W 0 pings 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 0 pings S 2 pings S 0 pings M 0 pings 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
No pings yet today
No pings yesterday
Amazonbot 8 Perplexity 4 Unknown AI 3 ChatGPT 1 Google 1 Meta AI 1 Ahrefs 1
crawler 19
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Low
⚡ Quick Fix
Replace any hardcoded number/string with a named class constant or enum. Group related constants in an enum or dedicated constants class.
📦 Applies To
web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
[^a-z][2-9][0-9]+|[^a-z][0-9]{4}
Auto-detectable: ✓ Yes phpmd phpcs eslint
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Medium ✗ Manual fix Fix: Low Context: File

✓ schema.org compliant