简体   繁体   English

Laravel 中的闭包是什么?

[英]What is Closure in Laravel?

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 Closure and what does it do?什么是Closure ,它有什么作用?

A Closure is 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 Closure parameter the handle function.我们首先在handle函数中添加一个Closure参数。 This will type hint us that the handle function takes a Closure .这将提示我们handle函数采用Closure

We then call the handle function and pass a function as the first parameter.然后我们调用handle函数并传递一个函数作为第一个参数。

By using $closure();通过使用$closure(); in the handle function we tell PHP to execute the given Closure which will then echo 'Hello!'handle函数中,我们告诉 PHP 执行给定的Closure ,然后echo 'Hello!'

It is also possible to pass parameters into a Closure .也可以将参数传递到Closure We can do so by changing the Closure call in the handle function to pass on a parameter.我们可以通过更改handle函数中的Closure调用来传递参数来实现。 In this example i'll just pass a string but this can be any variable.在这个例子中,我将只传递一个字符串,但这可以是任何变量。

The handle function now looks like句柄函数现在看起来像

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

We now also need to modify the Closure itself to take the parameter.我们现在还需要修改Closure本身以获取参数。 We do so by simply adding a parameter to the function.我们通过简单地向函数添加一个参数来实现。 And then we pass that variable to the echo .然后我们将该变量传递给echo

The function now looks like该功能现在看起来像

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

Which will echo Hello World!这将与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM