konohanaruto
konohanaruto

Reputation: 63

The Scoping of Static Variables in PHP Anonymous Functions

I have some trouble,When I define a static variable in a method and call it multiple times, the code is as follows:

function test() 
{
    static $object;

    if (is_null($object)) {
        $object = new stdClass();
    }

    return $object;
}

var_dump(test());
echo '<hr>';
var_dump(test());

The output is as follows:

object(stdClass)[1]
object(stdClass)[1]

Yes, they return the same object.

However, when I define a closure structure, it returns not the same object.

function test($global)
{
    return function ($param) use ($global) {
        //echo $param;
        //exit;
        static $object;

        if (is_null($object)) {
            $object = new stdClass();
        }

        return $object;
    };
}

$global = '';

$closure = test($global);
$firstCall = $closure(1);

$closure = test($global);
$secondCall = $closure(2);

var_dump($firstCall);
echo '<hr>';
var_dump($secondCall);

The output is as follows:

object(stdClass)[2]
object(stdClass)[4]

which is why, I did not understand.

Upvotes: 4

Views: 1079

Answers (1)

Jeremy Lawson
Jeremy Lawson

Reputation: 483

By calling test(...) twice in your sample code, you have generated two distinct (but similar) closures. They are not the same closure.

This becomes more obvious some some subtle improvements to your variable names

$closureA = test($global);
$firstCall = $closureA(1);

$closureB = test($global);
$secondCall = $closureB(2);

var_dump($firstCall, $secondCall);

Now consider this code alternative:

$closureA = test($global);
$firstCall = $closureA(1);

$secondCall = $closureA(2);

var_dump($firstCall, $secondCall);

Does that help you understand?

Upvotes: 5

Related Questions