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 中的闭包是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)