我对 PHP 闭包有点困惑。有人可以帮我解决这个问题:
// Sample PHP closure
my_method(function($apples) use ($oranges) {
// Do something here
});
我应该使用它们以及何时使用它们$apples
之间有什么区别?$oranges
$apples
将采用在调用时传递给函数的值,例如
function my_method($callback) {
// inside the callback, $apples will have the value "foo"
$callback('foo');
}
$oranges
$oranges
将引用存在于定义闭包的范围内的变量的值。例如:
$oranges = 'bar';
my_method(function($apples) use ($oranges) {
// $oranges will be "bar"
// $apples will be "foo" (assuming the previous example)
});
区别在于定义$oranges
函数时绑定和调用函数时绑定。$apples
闭包可以让你访问定义在函数之外的变量,但是你必须明确告诉 PHP 哪些变量应该可以访问。global
如果变量是在全局范围内定义的,这与使用关键字类似(但不等价!) :
$oranges = 'bar';
my_method(function($apples) {
global $oranges;
// $oranges will be "bar"
// $apples will be "foo" (assuming the previous example)
});
使用闭包和 的区别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
$apples
作为参数传递给my_method
, 并被$oranges
注入内部。