小编kon*_*uto的帖子

PHP匿名函数中静态变量的作用域

我遇到了麻烦,当我在一个方法中定义一个静态变量并多次调用时,代码如下:

function test() 
{
    static $object;

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

    return $object;
}

var_dump(test());
echo '<hr>';
var_dump(test());
Run Code Online (Sandbox Code Playgroud)

输出如下:

object(stdClass)[1]
object(stdClass)[1]
Run Code Online (Sandbox Code Playgroud)

是的,它们返回相同的对象。

但是,当我定义闭包结构时,它返回的对象并不相同。

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);
Run Code Online (Sandbox Code Playgroud)

输出如下:

object(stdClass)[2]
object(stdClass)[4]
Run Code Online (Sandbox Code Playgroud)

这就是为什么,我不明白。

php variables static closures

4
推荐指数
1
解决办法
573
查看次数

标签 统计

closures ×1

php ×1

static ×1

variables ×1