Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php closure in anonymous function and reference &

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:

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

  2. 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!

like image 360
Robert Rocha Avatar asked Oct 07 '14 01:10

Robert Rocha


1 Answers

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.

like image 63
georg Avatar answered Oct 26 '22 23:10

georg