匿名函数的use()语句

时间:2015-04-04 22:00:25

标签: php anonymous-function

使用它是不好的做法吗?

因为人们说全局变量是不好的做法,使用的东西会把变量从外部带入函数中,所以它就像全局变量

这就是它的外观

$a = 1;
$func = function() use($a){
  print $a;
};

1 个答案:

答案 0 :(得分:2)

匿名函数的“use”参数中定义的任何参数都使用定义匿名函数时的值;所以他们必须存在;但是在调用函数时,它们不需要传递(甚至存在于调用者范围内)。

function myFunctionCreator() {
    $a = 1; // Must exist for the `use` clause
    $func = function() use($a){
        echo $a, PHP_EOL;
    };
    return $func;
}

$myFunc = myFunctionCreator();
$a = 2;

$myFunc(); // echoes 1 (value of $a at the point where the function was created)

从上面的示例中可以看出,$a在定义函数的位置具有值1,即使具有相同名称的变量存在于调用函数,它是函数调用中使用的原始$a(值1)。


定义函数时,主参数定义中定义的参数不需要存在,但必须在调用函数时将值作为参数传递给函数。

function myFunctionCreator() {
    $a = 1; // Need not exist, and will be ignored
    $func = function($a) {
        echo $a, PHP_EOL;
    };
    return $func;
}

$myFunc = myFunctionCreator();
$value = 2;

$myFunc($value);  // echoes 2 (value of $a explicitly passed to the function call
                  //           at the time it is executed)

所以这两种类型的行为是完全不同的,它们的组合目的提供了一定程度的灵活性,这是非常不同的


正如Rizier123在他的评论中提到的,作为“标准”传递给匿名函数的参数可以有默认值,类型提示等,而“使用”参数不能。

function myFunctionCreator() {
    $func = function(array $dataset = [1,2,3]) {
        foreach($dataset as $value) {
            echo $value, PHP_EOL;
        }
    };
    return $func;
}

$myFunc = myFunctionCreator();
$value = ['a','b','c'];

$myFunc($value);
$myFunc();
$myFunc(['x','y','z']);

或者(如第三次调用所示,参数可以直接传递。

这些应用于“use”参数的Andy会导致解析错误