Reputation: 16214
Below is the code which outputs "15", why?
function zz(&$x){
$x = $x + 5;
}
$x = 10;
zz($x);
echo $x;
Please explain
Upvotes: 3
Views: 362
Reputation: 1026
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.
Upvotes: 1
Reputation: 1577
$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.
Upvotes: 1
Reputation: 3828
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!
Upvotes: 3
Reputation: 1216
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.
Upvotes: 1
Reputation: 449525
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.
Upvotes: 6
Reputation: 816600
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.
Upvotes: 2