简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM