在PHP中使用use函数有什么好处?

时间:2014-02-15 09:11:05

标签: php closures

如果以这种方式写我的回调函数......

$direction = 'asc';      
$compare = function ($a, $b) use ($direction) {
...

...然后脚本显示与此相同的行为:

$direction = 'asc';      
$compare = function ($a, $b, $direction = 'asc') {
...

在这两种情况下,变量都按值传递。 那么,使用use-function而不是通过标准函数参数传递变量有什么好处?

2 个答案:

答案 0 :(得分:1)

$compare = function ($a, $b, $direction = 'asc') { ... };

这是一个普通函数,它接受3个参数,最后一个是可选的。它需要被称为:

$compare('foo', 'bar', 'desc');

下面:

$direction = 'asc';      
$compare = function ($a, $b, $direction = 'asc') { ... };

两个$direction变量完全没有任何关系。

如果你这样做:

usort($array, $compare)

然后usort只会使用两个参数调用$compare,它永远不会传递第三个参数,它始终保持默认值asc

$direction = 'asc';      
$compare = function ($a, $b) use ($direction) { ... };

此处$direction变量实际包含在函数中。

$direction = 'asc';  -----------------+
                                      |
$compare = function ($a, $b) use ($direction) {
                                      |
    echo $direction;  <-------------- +
};

您正在将变量的范围扩展到函数中。这就是use的作用。另请参阅Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

答案 1 :(得分:0)

什么是use

use表示从当前范围继承变量或值。参数可以从任何地方给出,但use d变量只能在某些情况下存在。因此,您可能无法在范围之外使用闭包,其中未设置use d变量:

<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x)use($y){
    var_dump($x, $y);
};

$fn(1);
?>

节目:

Notice:  Undefined variable: y in script.php on line 4
int(1)
NULL

但是,您可以使用参数化闭包而不具有此范围依赖性:

<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x, $y = null){
    var_dump($x, $y);
};

$fn(1);
?>

查看相关问题: In PHP 5.3.0, what is the function "use" identifier?

有什么好处?

use构造的一个主要用例是使用闭包作为其他函数(方法)的回调。在这种情况下,您必须遵循固定数量的函数参数。因此,将额外参数(变量)传递给回调的唯一方法是use构造。

<?php
header('Content-Type: text/plain; charset=utf-8');

$notWannaSeeThere = 15;
$array  = [ 1, 15, 5, 45 ];
$filter = function($value) use ($notWannaSeeThere){
    return $value !== $notWannaSeeThere;
};

print_r(array_filter($array, $filter));
?>

节目:

Array
(
    [0] => 1
    [2] => 5
    [3] => 45
)

在这个例子中,$filter使用array_filter()闭包只用一个参数调用 - 数组元素值(我们“不能”强制它使用额外的参数)。尽管如此,我们仍然可以传递addl变量,这些变量可以在父范围内使用。

参考: anonymous functions

  

从父作用域继承变量与使用不同   全局变量。

相关问题