Forum Moderators: coopster

Message Too Old, No Replies

Pass variable into function by reference

don't want to use global

         

mcibor

8:43 pm on Jan 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi!

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!

ara818

7:36 am on Jan 24, 2005 (gmt 0)

10+ Year Member



Perhaps, I'm not understanding, but this should do it:
$a = my_f($c, $b)

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.