function passed with argument as "& $x" outputs a value rather than error see the code below
Below is开发者_Go百科 the code which outputs "15", why?
function zz(&$x){
$x = $x + 5;
}
$x = 10;
zz($x);
echo $x;
Please explain
Works as designed. By using &
you pass $x
by reference, meaning that anything the function does to the variable, will be done to the original $x
that is set to 10
.
If you used
function zz($x)
the original $x
would stay at 10
, because only the variable value is passed to the function.
you are passing the value as argument is not direct value of the variable but its passing By reference, so its giving you 15 as a output.
Thanks!
Because the function signature defines that the value passed to the function should be passed by reference.
If you don't know what that means, I suggest to read this paragraph on Wikipedia.
Adding a & means you are passing the $x variable by reference. The value outside is changed within the function, instead of a copy within the function being changed.
$x
inside the function is a reference to the same value as $x
outside your function.
When a function accepts a parameter with a "&", it's value is not copied into the new variable created inside the function's scope, but is a reference to the same value as the argument that was given.
See here.
Using & Ampersand: Passing by Reference mets the purpose in the function.
Its simply alter the original variable and return it again to the same variable name with its new value assigned.
精彩评论