OM The Eternity
OM The Eternity

Reputation: 16214

function passed with argument as "& $x" outputs a value rather than error see the code below

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

Answers (6)

Webrsk
Webrsk

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

Gipsy King
Gipsy King

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

Chandresh M
Chandresh M

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

SorcyCat
SorcyCat

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

Pekka
Pekka

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

Felix Kling
Felix Kling

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

Related Questions