什么是拉拉维尔的闭包?
我在中间看到一个Laravel函数:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check())
{
return redirect('/home');
}
return $next($request);
}
它是什么,它有什么作用?Closure
我在中间看到一个Laravel函数:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check())
{
return redirect('/home');
}
return $next($request);
}
它是什么,它有什么作用?Closure
闭包是一个匿名函数。闭包通常用作回调方法,并且可以用作函数中的参数。
如果采用以下示例:
function handle(Closure $closure) {
$closure();
}
handle(function(){
echo 'Hello!';
});
我们首先在函数中添加一个参数。这将键入提示我们该函数采用 .Closure
handle
handle
Closure
然后,我们调用该函数并将函数作为第一个参数传递。handle
通过在函数中使用,我们告诉PHP执行给定的,然后$closure();
handle
Closure
echo 'Hello!'
还可以将参数传递到 .我们可以通过更改函数中的调用来传递参数来执行此操作。在此示例中,我将只传递一个字符串,但这可以是任何变量。Closure
Closure
handle
句柄函数现在看起来像
function handle(Closure $closure) {
$closure('Hello World!');
}
我们现在还需要修改自身以采用参数。我们只需向函数添加一个参数即可。然后我们将该变量传递给 .Closure
echo
该函数现在看起来像
handle(function($value){
echo $value;
});
这将回声Hello World!
有关更多信息,您可以查看以下链接: