Reputation: 181
I know that using & before a function's parameter means it's passed by reference, and can be used for output, but what does it mean if I use it in another context?
For example:
function foo (&$param) {
$param = 3;
}
foo (&$a);
echo $a;
I added the & when calling foo just to see what happens, and it didn't actually appear to change anything, and $a isn't even defined before that point.
Could anyone please explain that?
Upvotes: 0
Views: 706
Reputation: 33502
When you use &$param
in a function it mean you pass by reference. You however shouldn't use it in the function call - with current versions of PHP, this will generate a warning. Function calls are only allowed to pass a variable now. The function declaration must be indicative of whether the function accepts the argument by reference or by passing.
Pass it as per the docs functionName($variableName);
rather than functionName(&$variableName)
A function called with an &$
parameter will now generate a warning, which can be suppressed, but is still a depreciated way to call.
Upvotes: 3
Reputation: 4478
Well consider a code below, This may not answer your question but a good example to understand the referenced variable.
<?
$variable="this is some test";
$refvariable = &$variable;
$nvariable = $variable;
$variable ="This IS ANOTHER VARIABLE STRING";
echo "Referenced Variable=".$refvariable;
echo "<bR>Normal Variable=".$nvariable;
?> In simple words, above $nvariable is the normal variable, when its echoed it takes the value of $variable set initially. Now consider $refvariable which is referenced variable, it takes the latest value of $variable. Hope above example help you understand.
Upvotes: 0
Reputation: 88647
The manual says:
Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use
&
infoo(&$a);
.
Further to this, as of 5.4.0 you will actually get a parse error. Before that it will work but since 5.3 it will complain about. Since there are some native functions that actually require call-time pass-by-reference (for example debug_zval_dump()
and underneath call_user_func()
and call_user_func_array()
) this aspect of 5.4 degrades badly.
Upvotes: 7