What is the difference between passing a variable by value and by reference in PHP?
Last updated
By value (the default) passes a copy, so changes inside a function don't affect the caller; by reference passes an alias to the same variable, so changes propagate back.
By value (default):
The function gets its own copy; mutating it leaves the original untouched.
PHP uses copy-on-write internally, so a copy isn't physically duplicated until it's modified.
By reference (using
&):Prefix the parameter with
&so the parameter and argument point to the same value.Reassigning or mutating it inside the function changes the caller's variable.
Objects are a special case: Even passed by value, an object variable holds a handle, so mutating the object's properties affects the original; only reassigning the variable to a new object differs.
[lang:php]
function addOne($x) { $x++; } // by value
function addOneRef(&$x) { $x++; } // by reference
$n = 5;
addOne($n); // $n is still 5
addOneRef($n); // $n is now 6
- https://stackoverflow.com/questions/879/are-php-variables-passed-by-value-or-by-reference
- https://www.tutorialspoint.com/article/what-is-pass-by-reference-and-pass-by-value-in-php
- https://freek.dev/2801-pass-by-reference-vs-pass-by-value-in-php-whats-the-real-difference
- https://forum.freecodecamp.org/t/use-recursion-to-create-a-countdown-why-is-this-not-working/326099
- https://stackoverflow.com/questions/39512193/passing-by-reference-vs-passing-by-value