Replace Magic Literal with Symbolic Constant
debt(d3/e2/b3/t3)
Closest to 'default linter catches the common case' (d3), phpmd and phpcs both have magic number detection rules enabled in standard rulesets.
Closest to 'one-line patch' (e1), slightly above because grounded in quick_fix: replace literal with named constant, but may require defining the constant elsewhere first, so e2.
Closest to 'localised tax' (b3), constants classes/enums become a small ongoing structural commitment, but applies broadly across web/cli/queue contexts per applies_to.
Closest to 'minor surprise' (t3), grounded in misconception: developers over-apply the rule and create noise constants like CONST_42=42, a documented gotcha but not catastrophic.
TL;DR
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
Why It Matters
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
if ($attempts > 3) { sleep(30); } // What are 3 and 30?
if ($status === 'pnd') { } // What is 'pnd'?
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';
}