4

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.

1

1 Answer 1

5

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.