References
Assign by reference
Ampersand links two names to one value. Writing through either name updates the shared slot.
Objects already share state without this trick, so plain variables are the main case for explicit links.
$a = 10;
$b = &$a;
$b = 20;
echo $a;
Loop by reference + unset
A foreach value with ampersand edits the array in place. Each turn writes straight into the source slot.
Always unset the loop variable right after such a loop so later reuse does not overwrite the last item by accident.
$nums = [1, 2, 3];
foreach ($nums as &$v) {
$v = $v * 2;
}
unset($v);
print_r($nums);
Return by reference
A function with ampersand in its signature can return a slot instead of a copy. Callers then bind and update the original through the result.
Both sides need ampersand: one on the function and one on the receiving assign.
$store = ["n" => 1];
function &getSlot(array &$row): int {
return $row["n"];
}
$slot = &getSlot($store);
$slot = 42;
echo $store["n"];
Avoid mostly
References add hidden links that are hard to trace. Most tasks read better with plain returns and fresh arrays.
Reach for return values first and reserve reference tricks for tight loops and small helpers only.
$nums = [1, 2, 3];
$doubled = array_map(fn($v) => $v * 2, $nums);
print_r($doubled);
print_r($nums);
Next: Static scope
Автор статьи: Arthur Isaev