I’m just trying to understand passing by reference in PHP by trying some examples found on php.net. I have one example right here found on the php website but it does not work:
function foo(&$var)
{
return $var++;
}
$a=5;
echo foo($a); // Am I not supposed to get 6 here? but I still get 5
This is an example found here
Can anybody tell me why am I getting 5 instead of 6 for the variable $a?
Your code and the example code is not the same. Is it a wonder they behave differently?
To see the behavior you expect, you have to change
$var++to++$var.What happens here is that while the value of
$ais 6 after the function returns, the value that is returned is 5 because of how the post-increment operator ($var++) works. You can test this with: