PHP 7 interview question · Most asked

How do references (`&`) work in PHP?

Summary

A reference makes two names point to the same variable container, so changing one changes the other. You can assign by reference, pass by reference (function f(&$x)), and return by reference.

Longer Answer

References are not pointers; you can't do arithmetic on them. Objects don't need references to be modified inside functions, because object handles are already shared. Overusing references hurts readability and can defeat copy-on-write. A classic bug is the dangling reference after foreach ($arr as &$v).

Code Example

<?php
function addTax(array &$prices, float $rate): void
{
    foreach ($prices as &$p) {
        $p *= (1 + $rate);
    }
    unset($p);
}

Key Points

  • Aliases to the same value container
  • Objects are already passed by handle
  • Unset loop references after foreach
  • Prefer return values over by-ref params

More most-asked PHP 7 questions

← All PHP 7 questions