PHP 函数使用 use / global 返回匿名函数

PHP function returning anonymous function with use / global

我是 PHP 的新手,目前正在学习闭包的概念。

对于使用 use() 关闭,我知道我可以执行以下操作:

$y = "hello"; 
$c = function() use ($y) {
    return $y; 
}; 

print_r($c()); // prints out 'hello'
echo '<br />'; 

但是,我在执行 return 另一个匿名函数的函数时遇到问题,例如:

$u = function() {
    return function () use ($y) {
        return $y; 
    }; 
}; 

print_r($u()); // empty closure object...
echo '<br />'; 

我知道当我将上面的代码修改为下面的代码时,代码可以完美运行。但是我不明白为什么。

$b = function() use ($y) {
    return function () use ($y) {
        return $y; 
    };
}; 

print_r($b()); // output :  [y] => hello
echo'<br />'; 

以类似的方式,我对以下使用全局的代码有疑问,为什么它不起作用:

$k = function() {
    return function() {
        global $y; 
        return $y; 
    }; 
}; 

print_r($k()); // prints out 'Closure Object ( )'
echo '<br />'; 

请不要告诉我如何交换代码以使其工作。正如我所尝试的那样,我知道如何更改并使这些代码起作用。相反,我想知道为什么当我在另一个匿名函数的 return 中调用它们时 global 和 use() 不起作用。

I know that when I modify the above codes to the below one, then the code works perfectly. BUT I do NOT understand the reason why. Hope someone can explain it to me.

它没有像您预期的那样工作的原因是因为您的闭包正在 return另一个闭包。

您不能调用取消引用闭包,但请考虑如何 it will work:

$k = function() {
    return function() {
        global $y; 
        return $y; 
    }; 
}; 

$first = $k();
print_r($first); // it's a closure, because your main closure returns another closure
$second = $first();
print_r($second); // here is "hello" as you expect

以下将不起作用:

print_r($k()());

在你 use $y 不存在的情况下,return 使用未定义变量的闭包的过程实际上会在原始变量上创建静态 属性带有空值的闭包,这就是您看到此输出的原因:

var_dump($u());

object(Closure)#2 (1) {
  ["static"]=>
  array(1) {
    ["y"]=>
    NULL
  }
}

注意如果你用error reporting on做上面的事情你也会得到一个未定义的变量错误。

您似乎已经知道了,但我还是要提一下 $y 在闭包内不可访问,因为它在函数的范围之外。这就是为什么当你使用 global 注册它时它会 return 你所期望的,当你从外部闭包 use 它时也是如此。