Forum Moderators: coopster
There was a nice discussion about functions, and there I learned that in PHP it's possible to pass variables through reference as well.
I have a function that needs to change two values: a and b
I can do that through global:
function my_f($c)
{
global b;
$a = 2 * $c;
$b = $b + $c;
return $a;
}$b = 1;
$c = 2;
$a = my_f($c);//a = 4; b = 3;
With reference I can't call the function without getting an error, ar at least warning:
function my_f($c, &$b)
{
$a = 2 * $c;
$b = $b + $c;
return $a;
}$b = 1;
$c = 2;
$a = my_f($c, no idea what to put here);//a = 4; b = 3;
Please help!
In PHP, to pass by reference, you just need to declare your function as you already did, you don't need to do anything on the calling side.
Be warned though. Because of this, once you have declared a function as taking in references, PHP will throw an error if you use constants.
For example
$a = my_f($c, $b) will work.
but
$a = my_f($c, 3) will not.