Do you use '&' before the parameter name in PHP?
Mariusz Malek
Posted on September 21, 2022
In my career, when I was meeting a new PHP developer or working on any project, I haven't seen too many people using '&' in front of a parameter name.
Even when I started my adventure with PHP, I didn't hear about it. I think this is a great time to remind the community about the "&".
Ind documentation we can read
You can pass a variable by reference to a function so the function can modify the variable
function foo(&$var)
{
$var++;
}
$a=5;
foo($a); // $a is 6 here
This means that the function gets a reference to the original value of $var, not a copy of that value. Example:
function more(&$num) { $num++; }
$number = 0;
more($number);
echo $number; // this outputs "1"
💖 💪 🙅 🚩
Mariusz Malek
Posted on September 21, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.