PHP use() function for scope?

自闭症网瘾萝莉.ら 提交于 2019-11-28 00:31:15

问题


I have seen code like this:

function($cfg) use ($connections) {}

but php.net doesn't seem to mention that function. I'm guessing it's related to scope, but how?


回答1:


use is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the 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
}

For example:

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

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

// $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');



回答2:


It is telling the anonymous function to make $connections (a parent variable) available in its scope.

Without it, $connections wouldn't be defined inside the function.

Documentation.



来源:https://stackoverflow.com/questions/7885513/php-use-function-for-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!