问题描述
我在中间看到了一个 Laravel 函数:
I saw one Laravel function in middlewere:
public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { return redirect('/home'); } return $next($request); }
什么是Closure,它有什么作用?
What is Closure and what does it do?
推荐答案
A 关闭 是一个匿名函数.闭包通常用作回调方法,并且可以用作函数中的参数.
A Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function.
如果你看下面的例子:
function handle(Closure $closure) { $closure(); } handle(function(){ echo 'Hello!'; });
我们首先在 handle 函数中添加一个 Closure 参数.这将提示我们 handle 函数接受一个 Closure.
We start by adding a Closure parameter the handle function. This will type hint us that the handle function takes a Closure.
然后我们调用 handle 函数并传递一个函数作为第一个参数.
We then call the handle function and pass a function as the first parameter.
通过在 handle 函数中使用 $closure(); 我们告诉 PHP 执行给定的 Closure 然后 echo'你好!'
By using $closure(); in the handle function we tell PHP to execute the given Closure which will then echo 'Hello!'
也可以将参数传递到 Closure.我们可以通过更改 handle 函数中的 Closure 调用来传递参数来实现.在这个例子中,我将只传递一个字符串,但这可以是任何变量.
It is also possible to pass parameters into a Closure. We can do so by changing the Closure call in the handle function to pass on a parameter. In this example i'll just pass a string but this can be any variable.
handle 函数现在看起来像
The handle function now looks like
function handle(Closure $closure) { $closure('Hello World!'); }
我们现在还需要修改 Closure 本身以获取参数.我们通过简单地向函数添加一个参数来实现.然后我们将该变量传递给 echo.
We now also need to modify the Closure itself to take the parameter. We do so by simply adding a parameter to the function. And then we pass that variable to the echo.
函数现在看起来像
handle(function($value){ echo $value; });
哪个将回显 Hello World!
有关更多信息,您可以查看以下链接:
For more information you can check out these links:
http://php.net/manual/en/functions.anonymous.php
http://php.net/manual/en/class.closure.php