在PHP闭包中与“使用"标识符混淆 [英] Confusion with 'use' identifier in PHP closures
问题描述
我对PHP闭包有点困惑.有人可以帮我解决这个问题吗?
I'm a little confused with PHP closures. Can someone clear this up for me:
// Sample PHP closure
my_method(function($apples) use ($oranges) {
// Do something here
});
$apples
和$oranges
有什么区别?什么时候应该使用它们?
What's the difference between $apples
and $oranges
and when should I be using each?
推荐答案
$apples
将采用调用该函数时传递给该函数的值,例如
$apples
will take on the value that is passed to the function when it is called, e.g.
function my_method($callback) {
// inside the callback, $apples will have the value "foo"
$callback('foo');
}
$oranges
将引用变量$oranges
的值,该变量存在于您定义闭包的范围内.例如:
$oranges
will refer to the value of the variable $oranges
which exists in the scope where you defined the closure. E.g.:
$oranges = 'bar';
my_method(function($apples) use ($oranges) {
// $oranges will be "bar"
// $apples will be "foo" (assuming the previous example)
});
不同之处在于,在定义时绑定了$oranges
,在称为时绑定了$apples
.
The differences is that $oranges
is bound when the function is defined and $apples
is bound when the function is called.
闭包使您可以访问在函数外部定义的变量,但是您必须明确告诉PHP应该可以访问哪些变量.如果变量是在全局范围内定义的,则与使用global
关键字相似(但不等同!).
Closures let you access variables defined outside of the function, but you have to explicitly tell PHP which variables should be accessible. This is similar (but not equivalent!) to using the global
keyword if the variable is defined in global scope:
$oranges = 'bar';
my_method(function($apples) {
global $oranges;
// $oranges will be "bar"
// $apples will be "foo" (assuming the previous example)
});
使用闭包和global
之间的区别:
The differences between using closures and global
:
- 您可以将 local 变量绑定到闭包,
global
仅适用于全局变量. -
闭包绑定定义时变量的值.定义函数后,对变量所做的更改不会对其产生影响.
另一方面,如果使用global
,则将在调用的那一刻收到变量具有的值.
- You can bind local variables to closures,
global
only works with global variables. Closures bind the value of the variable at the time the closure was defined. Changes to the variables after the function was defined does not effect it.
On the other hand, if you useglobal
, you will receive the value the variable has at the moment when the function is called.
示例:
$foo = 'bar';
$closure = function() use ($foo) {
echo $foo;
};
$global = function() {
global $foo;
echo $foo;
};
$foo = 42;
$closure(); // echos "bar"
$global(); // echos 42
这篇关于在PHP闭包中与“使用"标识符混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!