与PHP闭包混淆 [英] Confusion with PHP closures

查看:120
本文介绍了与PHP闭包混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑与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 code> $ 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哪些变量应该是可访问的。如果变量在全局范围中定义,这与使用全局关键字类似(但不等效!):

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)
});

使用closures和 global 之间的区别:

The differences between using closures and global:


  • 您可以将 local 变量绑定到closures, 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 use global, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆