3

Below is the code which outputs "15", why?

function zz(&$x){

$x = $x + 5;

}

$x = 10;

zz($x);
echo $x;

Please explain

OM The Eternity
  • 15,694
  • 44
  • 120
  • 182

6 Answers6

6

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
3

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!

Chandresh M
  • 3,808
  • 1
  • 24
  • 48
2

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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.

SorcyCat
  • 1,206
  • 10
  • 19
1

$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.

Gipsy King
  • 1,549
  • 9
  • 15
1

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.

Webrsk
  • 1,014
  • 2
  • 15
  • 24