Can't understand function and reference behaviour

Viewed 86

I have this code.

$add = (function () {
    $counter = 0;
    return function () use(&$counter) {return $counter += 1;};
})();

echo $add(); //1
echo $add(); //2
echo $add(); //3

Expected Output:

111

Original Output:

123

Inside the function $counter=0 is assigned by 0 so the &$counter should be 0.
So when i called it second time it sees $counter=0 and so that &$counter will be 0, Isn't it?
Why it is incrementing?

3 Answers

It does not call $counter=0 for the second time. You call it just once when initiating the first function. When you call $add(), you call every time the second function (that is in your return statement) which just uses the modified value of $counter that you passed by reference. If you would add echo $counter; after the $counter = 0; you will see that.

What do you mean by "sees"? The first time you execute $add(), the inner counter is counted up. As you used a reference pointer (through adding the ampersand in use(&$counter)) to the original $counter, this is also manipulated, so after executing this once, the counter variable no longer contains a zero.

When you remove that ampersand, the innermost function uses a fresh counter each and every time, such that your expected output is met

Because you pass a reference to the function the initial $counter = 0; value is also increased each time you add 1 to it using $counter += 1; that's why your result is "123".

To get "111" you need to pass a variable to a function $counter, not a reference.

Related