PHP use()函数用于范围?

kri*_*sen 9 php syntax anonymous-function

我见过这样的代码:

function($cfg) use ($connections) {}
Run Code Online (Sandbox Code Playgroud)

但是php.net似乎没有提到这个功能.我猜它与范围有关,但是怎么样?

dec*_*eze 17

use它不是一个函数,它是Closure语法的一部分.它只是使闭包内的外部作用域的指定变量可用.

$foo = 42;

$bar = function () {
    // can't access $foo in here
    echo $foo; // undefined variable
};

$baz = function () use ($foo) {
    // $foo is made available in here by use()
    echo $foo; // 42
}
Run Code Online (Sandbox Code Playgroud)

例如:

$array = array('foo', 'bar', 'baz');
$prefix = uniqid();

$array = array_map(function ($elem) use ($prefix) {
    return $prefix . $elem;
}, $array);

// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 6

它告诉匿名函数使$connections变量)在其范围内可用。

没有它,$connections就不会在函数内部定义。

文档