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
- What are typed properties in PHP 7.4?
- How do return type declarations work in PHP 7?
- What were the headline improvements of PHP 7.0 over PHP 5.6?
- Explain scalar type declarations and coercive vs strict mode in PHP 7.
- Explain the `Throwable`, `Error` and `Exception` hierarchy introduced in PHP 7.
- What are nullable types in PHP 7.1?
- What does the null coalescing operator `??` do, and how is it different from `isset()` with a ternary?
- What are arrow functions in PHP 7.4 and how do they differ from closures?