Skip to content
Advertisement

Can’t understand function and reference behaviour

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement