I have:
function outside( $limit ) {
$tally = 0;
return function() use ( $limit, &$tally ) {
$tally++;
if( $tally > $limit ) {
echo "limit has been exceeded";
}
};
}
$inside = outside( 2 );
$inside();
$inside();
$inside();
Outputs: limit has been exceeded
My understanding:
on $inside = outside( 2 );
this returns the anonymous function and
assigns it to the variable$inside
. The anonymous function uses the
value of $limit
(2) and $tally
(0).
function $inside()
is called. This increments $tally
to 1
The
value is remembered somehow and so is $limit
. What is the purpose
of the ampersand before $tally
? I know it's used to create
references but in this context it confuses me. How can this closure
remember the value of $limit
?
Any references to official documentation would help!
Anonymous functions are actually Closure
objects in php. If you add var_dump($invoke)
to your code, you'll see this:
object(Closure)#1 (1) {
["static"]=>
array(2) {
["limit"]=>
int(2)
["tally"]=>
int(0)
}
}
use
'd variables are stored in the static
array in the closure object. When you invoke the closure, these variables are passed to the function, just like normal arguments. Therefore, if you don't use a reference, they will be passed by copying and any changes to them in the function will have no effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With