Undefined Variable and Null Coalescing Fixes
debt(d5/e1/b3/t5)
Closest to 'specialist tool catches' (d5), PHPStan/Psalm at level 4+ detect undefined variables; PHP 8 also raises warnings at runtime but they're easy to miss without static analysis.
Closest to 'one-line patch' (e1), quick_fix is to add ?? 'default' or isset() — a per-occurrence single-line change.
Closest to 'localised tax' (b3), applies wherever array/variable access happens; using ?? consistently is a minor ongoing habit but doesn't shape architecture.
Closest to 'notable trap' (t5), the misconception that undefined variable notices are harmless is a documented gotcha — they often mask real logic bugs and PHP 8 promoted them to warnings.
Also Known As
TL;DR
Explanation
PHP does not require variable declaration before use. Accessing a variable that has never been assigned returns null and triggers an E_NOTICE (PHP 5) or E_WARNING (PHP 7+). PHP 8 promoted this to a warning, making it more visible. The fix depends on context: use isset($x) before conditional use, $x ?? 'default' for a fallback value, or null coalescing assignment $x ??= 'default' to initialise only if not set. With PHPStan at level 6+, many undefined variable accesses are caught statically.
Common Misconception
Why It Matters
Common Mistakes
- Accessing $_GET['key'] without isset() or ??
- Using a loop variable after the loop where it may not be set
- Not initialising accumulator variables before loops
- Relying on PHP returning null silently rather than making intent explicit
Code Examples
<?php
echo $username; // Notice: Undefined variable
<?php
$username = $_SESSION['username'] ?? 'Guest';
echo $username; // Always defined
// Or check first:
if (isset($username)) { echo $username; }