php Laravel 中的闭包是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47348081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:33:30  来源:igfitidea点击:

What is Closure in Laravel?

phplaravellaravel-5closures

提问by vishal ribdiya

I saw one Laravel function in middlewere:

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

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

    return $next($request);
}

What is Closureand what does it do?

Closure它是什么以及它有什么作用?

回答by Amando Vledder

A Closureis an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function.

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

If you take the following example:

如果你看下面的例子:

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

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

We start by adding a Closureparameter the handlefunction. This will type hint us that the handlefunction takes a Closure.

我们首先Closurehandle函数添加一个参数。这将提示我们该handle函数采用Closure.

We then call the handlefunction and pass a function as the first parameter.

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

By using $closure();in the handlefunction we tell PHP to execute the given Closurewhich will then echo 'Hello!'

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

It is also possible to pass parameters into a Closure. We can do so by changing the Closurecall in the handlefunction to pass on a parameter. In this example i'll just pass a string but this can be any variable.

也可以将参数传递到Closure. 我们可以通过更改函数Closure中的handle调用来传递参数来实现。在这个例子中,我将只传递一个字符串,但这可以是任何变量。

The handle function now looks like

句柄函数现在看起来像

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

We now also need to modify the Closureitself to take the parameter. We do so by simply adding a parameter to the function. And then we pass that variable to the echo.

我们现在还需要修改Closure自身以获取参数。我们通过简单地向函数添加一个参数来实现。然后我们将该变量传递给echo.

The function now looks like

该功能现在看起来像

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

Which will echo Hello World!

哪个会回声 Hello World!

For more information you can check out these links:

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

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

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

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

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