Thursday, 29 December 2016

How does the "&" operator work in a PHP function?



Please see this code:




function addCounter(&$userInfoArray) {
$userInfoArray['counter']++;
return $userInfoArray['counter'];
}

$userInfoArray = array('id' => 'foo', 'name' => 'fooName', 'counter' => 10);
$nowCounter = addCounter($userInfoArray);

echo($userInfoArray['counter']);



This will show 11.



But! If you remove "&"operator in the function parameter, the result will be 10.



What's going on?


Answer



The & operator tells PHP not to copy the array when passing it to the function. Instead, a reference to the array is passed into the function, thus the function modifies the original array instead of a copy.



Just look at this minimal example:




function foo($a) { $a++; }
function bar(&$a) { $a++; }

$x = 1;
foo($x);
echo "$x\n";
bar($x);
echo "$x\n";

?>


Here, the output is:



1
2


– the call to foo didn’t modify $x. The call to bar, on the other hand, did.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...