Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand function and reference behaviour

Tags:

php

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?

like image 347
Anisur Rahman Avatar asked May 20 '26 10:05

Anisur Rahman


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

like image 111
Dmytro Huz Avatar answered May 21 '26 23:05

Dmytro Huz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!