与PHP闭包中的'use'标识符混淆

enc*_*nce 14 php closures

我对PHP闭包有点困惑.有人可以为我清除这个:

// Sample PHP closure
my_method(function($apples) use ($oranges) {
    // Do something here
});
Run Code Online (Sandbox Code Playgroud)

$apples$oranges每个人之间的区别是什么?

Fel*_*ing 16

$apples 将调用在调用函数时传递给函数的值,例如

function my_method($callback) {
    // inside the callback, $apples will have the value "foo"
    $callback('foo'); 
}
Run Code Online (Sandbox Code Playgroud)

$oranges将引用$oranges您定义闭包的作用域中存在的变量的值.例如:

$oranges = 'bar';

my_method(function($apples) use ($oranges) {
    // $oranges will be "bar"
    // $apples will be "foo" (assuming the previous example)
});
Run Code Online (Sandbox Code Playgroud)

的差异在于,$oranges在所述功能时被绑定定义$apples当函数被绑定称为.


闭包允许您访问在函数外部定义的变量,但您必须明确告诉PHP哪些变量应该可访问.global如果变量是在全局范围中定义的,那么使用关键字是类似的(但不等同!):

$oranges = 'bar';

my_method(function($apples) {
    global $oranges;
    // $oranges will be "bar"
    // $apples will be "foo" (assuming the previous example)
});
Run Code Online (Sandbox Code Playgroud)

使用闭包和之间的区别global:

  • 您可以将局部变量绑定到闭包,global仅适用于全局变量.
  • 闭包在绑定定义时绑定变量的.定义函数后对变量的更改不会影响它. 另一方面,如果使用,您将收到变量在调用函数时的值.
    global

    例:

    $foo = 'bar';
    $closure = function() use ($foo) { 
        echo $foo; 
    };
    $global = function() {
        global $foo;
        echo $foo;
    };
    
    $foo = 42;
    $closure(); // echos "bar"
    $global(); // echos 42
    
    Run Code Online (Sandbox Code Playgroud)