【发布时间】:2017-09-28 19:33:43
【问题描述】:
我最近浏览了这些匿名函数的例子,但我不是很清楚,它们之间有什么区别,为什么在第二个函数中
use keyword 使用过,为什么第一个返回 null 而第二个返回 0:
<?php
$result = 0;
// first function
$one = function()
{ var_dump($result); };
// second function with use
$two = function() use ($result)
{ var_dump($result); };
$three = function() use (&$result)
{ var_dump($result); };
$result++;
$one(); // outputs NULL: $result is not in scope
$two(); // outputs int(0): $result was copied
$three(); // outputs int(1)
?>
【问题讨论】:
-
您是否尝试运行您的示例?
-
通知是否被禁用?如果是这样,请激活它们以进行测试。
use允许您引用或使用匿名函数范围之外的变量。话虽如此,匿名函数有自己的范围(包括一些超级全局变量)。这意味着您无法访问此范围之外的任何内容。所以,如果你不声明它,你的变量将在 anon func 的范围内使用,因此它是NULL(如果你打开了通知,你会收到通知)。直接访问$result将允许您使用,但不能修改$result。&$result传递引用。 -
是的!我尝试了与提及相同的结果。
标签: php