PHP References (&$var)
debt(d7/e3/b3/t7)
Closest to 'only careful code review or runtime testing' (d7). PHPStan and phpcs can flag some reference patterns but the classic foreach-by-reference leak and unintended mutation bugs typically slip past default configs and surface only in review or when downstream code misbehaves.
Closest to 'simple parameterised fix' (e3). The quick_fix is to drop the & and rely on copy-on-write, or add unset($item) after foreach — usually a small localised change, occasionally touching a few call sites if the signature changes.
Closest to 'localised tax' (b3). References apply within specific functions/loops (applies_to spans all PHP contexts but the choice is per-function), imposing a small ongoing tax on readers of that code rather than shaping the whole system.
Closest to 'serious trap' (t7). The misconception (references improve performance) contradicts PHP's copy-on-write reality, and the foreach `&$item` dangling reference is a notorious gotcha — the obvious mental model is wrong in multiple ways.
Also Known As
TL;DR
Explanation
In PHP, references (&) make two or more variables aliases of the same underlying value container. Assigning to one changes the other. References appear in: variable assignment ($b = &$a), function parameters (function foo(&$x)), foreach by reference (foreach ($arr as &$val)), and global declarations. Common pitfalls: a reference created in a foreach loop persists after the loop ends — always unset($val) afterwards to avoid modifying the last element unexpectedly. Overuse of references in large functions creates implicit coupling and makes code hard to reason about; prefer returning values.
Watch Out
Common Misconception
Why It Matters
Common Mistakes
- foreach ($array as &$item) without unset($item) after the loop — the last element reference remains, corrupting the next use of $item.
- Passing large arrays by reference for performance — PHP uses copy-on-write; references can actually be slower.
- Not realising that assignment by reference ($b = &$a) makes both variables point to the same value.
- Using references to return multiple values from a function — return an array or value object instead.
Code Examples
foreach ($items as &$item) { $item['price'] *= 1.1; }
// $item still references $items[last] — next assignment corrupts it
foreach ($items as &$item) { $item['price'] *= 1.1; }
unset($item); // break the reference