Reputation: 20356
I have a simple question here. Is there a difference between passing a variable by reference in a function parameter like:
function do_stuff(&$a)
{
// do stuff here...
}
and do it inside the function like:
function do_stuff($a)
{
$var = &$a;
// do stuff here...
}
What are the differences (if any) between using these two?. Also, can anybody give me a good tutorial that explains passing by reference? I can't seem to grasp this concept 100%.
Thank you
Upvotes: 0
Views: 114
Reputation: 522625
In your first example, if you modify $a
inside the function in any way, the original value outside the function will be modified as well.
In your second example, whatever you do to $a
or its reference $var
will not modify the original value outside the function.
Upvotes: 1
Reputation: 8990
Here's a set of examples so you can see what happens with each of your questions. I also added a third function which combines both of your questions because it will also produce a different result.
function do_stuff(&$a)
{
$a = 5;
}
function do_stuff2($a)
{
$var = &$a;
$var = 3;
}
function do_stuff3(&$a)
{
$var = &$a;
$var = 3;
}
$a = 2;
do_stuff($a);
echo $a;
echo '<br />';
$a = 2;
do_stuff2($a);
echo $a;
echo '<br />';
$a = 2;
do_stuff3($a);
echo $a;
echo '<br />';
Upvotes: 1
Reputation: 360912
They're not at all equivalent. In the second version, you're creating a reference to an undefined variable $a
, causing $var
to point to that same null value. Anything you do to $var and $a inside the second version will not affect anything outside of the function.
In the first version, if you change $a inside the function, the new value will be present outside after the function returns.
Upvotes: 1
Reputation: 161657
In the second function, the $a
passed into the function is a copy of the argument passed in, (unless $a is an object), so you are making a $var
a reference to the $a
inside the function but it will still be separate from the variable passed to the function.
Assuming you are using a recent version of PHP, objects are automatically passed by reference too, so that could make a difference.
Upvotes: 0