Recently i was studying the “Passing by Reference”, I come to know following ways
What is the main difference between the following methods.
1.
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
2.
function foo($var)
{
$var++;
}
$a=5;
foo(&$a);
3.
function foo(&$var)
{
$var++;
}
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
even though all of them produce same results, and which is the best way to work with.
Thanks.
This accepts a parameter that is always passed by reference (the
&is infoo(&$var)). When$ais passed, it’s always as a reference, so incrementing the variable inside the function will cause the parameter to be modified.Do not use this. This is call-time pass-by-reference (you’re passing
&$a, a reference to$a, into the function), and is deprecated as of PHP 5.3.0. It’s bad practice because the function doesn’t expect a reference.This returns a reference (the
&is in&bar()) to a variable$adeclared in the functionbar(). It then takes a reference to the return value ofbar()and increments it. I’m not sure at a glance why this would be useful, though, especially for primitive/scalar types.