問題描述
我在中間看到了一個 Laravel 函數(shù):
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 關(guān)閉 是一個匿名函數(shù).閉包通常用作回調(diào)方法,并且可以用作函數(shù)中的參數(shù).
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
函數(shù)中添加一個 Closure
參數(shù).這將提示我們 handle
函數(shù)接受一個 Closure
.
We start by adding a Closure
parameter the handle
function. This will type hint us that the handle
function takes a Closure
.
然后我們調(diào)用 handle
函數(shù)并傳遞一個函數(shù)作為第一個參數(shù).
We then call the handle
function and pass a function as the first parameter.
通過在 handle
函數(shù)中使用 $closure();
我們告訴 PHP 執(zhí)行給定的 Closure
然后 echo'你好!'
By using $closure();
in the handle
function we tell PHP to execute the given Closure
which will then echo 'Hello!'
也可以將參數(shù)傳遞到 Closure
.我們可以通過更改 handle
函數(shù)中的 Closure
調(diào)用來傳遞參數(shù)來實現(xiàn).在這個例子中,我將只傳遞一個字符串,但這可以是任何變量.
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 函數(shù)現(xiàn)在看起來像
The handle function now looks like
function handle(Closure $closure) {
$closure('Hello World!');
}
我們現(xiàn)在還需要修改 Closure
本身以獲取參數(shù).我們通過簡單地向函數(shù)添加一個參數(shù)來實現(xiàn).然后我們將該變量傳遞給 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
.
函數(shù)現(xiàn)在看起來像
handle(function($value){
echo $value;
});
哪個將回顯 Hello World!
有關(guān)更多信息,您可以查看以下鏈接:
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
這篇關(guān)于Laravel 中的閉包是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!