如何在Laravel PHP中访问map函数外部的变量

Jan*_*ara 2 php laravel-5

public function test()
{
        $x = 10;
        $collection = collect([0, 10, 20]);

        $collection = $collection->map(function ($item, $key){

            return $item + $x;
        });
}
Run Code Online (Sandbox Code Playgroud)

我想访问函数中的$x变量map:怎么做?
当我尝试获取值时,我收到此错误消息:

ErrorException:未定义的变量:x

mad*_*ero 12

您需要使匿名函数使用use关键字继承变量.

你会像这样使用它:

$collection = $collection->map(function ($item, $key) use ($x) {

    return $item + $x;
});
Run Code Online (Sandbox Code Playgroud)