我遇到了麻烦,当我在一个方法中定义一个静态变量并多次调用时,代码如下:
function test()
{
static $object;
if (is_null($object)) {
$object = new stdClass();
}
return $object;
}
var_dump(test());
echo '<hr>';
var_dump(test());
输出如下:
object(stdClass)[1]
object(stdClass)[1]
是的,它们返回相同的对象。
但是,当我定义闭包结构时,它返回的对象并不相同。
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);
输出如下:
object(stdClass)[2]
object(stdClass)[4]
这就是为什么,我不明白。
通过在示例代码中两次调用test(...),您生成了两个不同的(但相似的)闭包。它们不是相同的闭包。
这对于变量名的一些细微改进变得更加明显
$closureA = test($global);
$firstCall = $closureA(1);
$closureB = test($global);
$secondCall = $closureB(2);
var_dump($firstCall, $secondCall);
现在考虑以下代码替代方案:
$closureA = test($global);
$firstCall = $closureA(1);
$secondCall = $closureA(2);
var_dump($firstCall, $secondCall);
这对您有帮助吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句