什么是拉拉维尔的闭包?

2022-08-30 12:26:24

我在中间看到一个Laravel函数:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check())
    {
       return redirect('/home');
    } 

    return $next($request);
}

它是什么,它有什么作用?Closure


答案 1

闭包是一个匿名函数。闭包通常用作回调方法,并且可以用作函数中的参数。

如果采用以下示例:

function handle(Closure $closure) {
    $closure();
}

handle(function(){
    echo 'Hello!';
});

我们首先在函数中添加一个参数。这将键入提示我们该函数采用 .ClosurehandlehandleClosure

然后,我们调用该函数并将函数作为第一个参数传递。handle

通过在函数中使用,我们告诉PHP执行给定的,然后$closure();handleClosureecho 'Hello!'

还可以将参数传递到 .我们可以通过更改函数中的调用来传递参数来执行此操作。在此示例中,我将只传递一个字符串,但这可以是任何变量。ClosureClosurehandle

句柄函数现在看起来像

function handle(Closure $closure) {
    $closure('Hello World!');
}

我们现在还需要修改自身以采用参数。我们只需向函数添加一个参数即可。然后我们将该变量传递给 .Closureecho

该函数现在看起来像

handle(function($value){
    echo $value;
});

这将回声Hello World!

有关更多信息,您可以查看以下链接:

http://php.net/manual/en/functions.anonymous.php

http://php.net/manual/en/class.closure.php


答案 2

推荐