Laravel 中的闭包是什么?

What is Closure in Laravel?(Laravel 中的闭包是什么?)
本文介绍了Laravel 中的闭包是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在中间看到了一个 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

这篇关于Laravel 中的闭包是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

In PHP how can you clear a WSDL cache?(在 PHP 中如何清除 WSDL 缓存?)
failed to open stream: HTTP wrapper does not support writeable connections(无法打开流:HTTP 包装器不支持可写连接)
Stop caching for PHP 5.5.3 in MAMP(在 MAMP 中停止缓存 PHP 5.5.3)
Caching HTTP responses when they are dynamically created by PHP(缓存由 PHP 动态创建的 HTTP 响应)
Memcached vs APC which one should I choose?(Memcached 与 APC 我应该选择哪一个?)
What is causing quot;Unable to allocate memory for poolquot; in PHP?(是什么导致“无法为池分配内存?在 PHP 中?)