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
to1
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!