Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

php - What is Closure in 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);
}

What is Closure and what does it do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. This will type hint us that the handle function takes a Closure.

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

By using $closure(); in the handle function we tell PHP to execute the given Closure which will then echo 'Hello!'

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.

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. We do so by simply adding a parameter to the function. And then we pass that variable to the echo.

The function now looks like

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

Which will echo 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...