Closing php in anonymous function and link &
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
Called$inside = outside( 2 );
returns an anonymous function and assigns it to a variable$inside
. The anonymous function uses the value$limit
(2) and$tally
(0). -
function
$inside()
. This increases$tally
to1
. The value is remembered somehow and so on$limit
. What is the purpose of the ampersand before$tally
? I know it was used to create but confuses me in this context. How does this closure remember the meaning$limit
?
Any links to the official documentation will help!
source to share
Anonymous functions are actually Closure
objects in php. If you add var_dump($invoke)
to your code, you will see this:
object(Closure)#1 (1) {
["static"]=>
array(2) {
["limit"]=>
int(2)
["tally"]=>
int(0)
}
}
use
The 'd variables are stored in an array static
in the closure object. When you call a closure, these variables are passed to the function as normal arguments. Therefore, if you do not use the link, they will be copied and any changes to them in the function will have no effect.
source to share
&
means you are passing the argument by reference, not by value. This means that you can change the variable inside the function, and it will be remembered outside - not only in this function.
By assigning a function $inside
, you are effectively keeping the variable reference intact, so it will be remembered from the call to be called.
source to share