Modern PHP new features series (v)--closures and anonymous functions

Source: Internet
Author: User

1. Overview

Closures and anonymous functions are introduced in PHP 5.3.0, and these two features are very useful and should be mastered by every PHP developer.

Closures are functions that encapsulate the surrounding state at creation time, even if the enclosing environment does not exist, and the state of encapsulation in the closure is still present.

An anonymous function is a function that has no name, an anonymous function can be assigned to a variable, and can be passed like any other PHP function object. However, the anonymous function is still a function, so it can be called, and it can be passed in as a callback for a function or method.

Note: In theory, closures and anonymous functions are different concepts, but PHP sees them as the same concept (the anonymous function is also called a closure function in PHP), so the following is referred to as the anonymous function of the closure, and vice versa.

2. Create a closed package

Creating closures is simple:

     

Results Print:

Hello laravelacademy.org

Closures are similar to normal PHP functions: Common syntax is the same, parameters are accepted, and values can be returned. However, the closure does not have a function name.

Note: We can call $greet variable because the value of this variable is a closure, and the closure object implements the __invoke () Magic method, and as long as the variable name has (), PHP will find and call the __invoke method.

We usually use PHP closures as callbacks to function methods, in fact, many PHP functions use closures, such as Array_map and Preg_replace_callback, which is a great time to use PHP anonymous functions. Remember that closures, like other values, can be passed into other PHP functions as parameters:

      

To implement such a function before a closure occurs, the PHP developer can only create a named function by itself, and then use the name to refer to the function:

       

This allows the implementation of callbacks to be separated from the place of use, and the use of closures to implement code is more concise.

3. Inherit variables from parent scope

You must manually invoke the BindTo method of the closure object in PHP or use the Using keyword to append the variables and states of the parent scope to the PHP closure. In practical applications, the use of using the keyword to achieve the majority.

Use keyword

In fact, closures are also used extensively in the Laravel framework, most commonly such as route definitions:

Route::group ([' domain ' = ' {account}.myapp.com '], function () {    route::get (' user/{id} ', function ($account, $id ) {        //    });});

The two function in this is a closed packet. The usage scenario for inheriting variables from the parent scope is also are cheap in the laravel underlying source code, such as the Saveorfail method for model.php (illuminate\database\eloquent):

The function of this method is to use a transaction to save the model data to the database, in which we use the closure to return to the save state, using the USE keyword to pass the $options of the parent scope to the closure so that it can access the data.

In addition, it is supported to pass multiple parent scope variables to closures, such as the Forcefill method in the Model class:

Multiple variables can be separated by commas.

BindTo Method

As we have mentioned earlier, closures are an object, so we can use the $this keyword in closures to get the internal state of the closure, the default state of the closure object is useless, it is important to note that the __invoke Magic method and BindTo method.

The role of __invoke has been previously stated that the __invoke () method is called automatically when an attempt is made to invoke an object in a way that invokes a function.

Next we look at the BindTo method, which allows us to bind the internal state of the closure to other objects. The second parameter of the BindTo method is particularly important here, which is to specify the PHP class to which the object that binds the closure belongs, so that the closure can access the protected and private member variables of the state closure object elsewhere.

You will find that the PHP framework often uses the BindTo method to map the route URL to an anonymous callback function, which binds the anonymous callback function to the Application object, so that the $this keyword can be used to refer to the important Application object in the anonymous function:

 
     routes[$routePath] = $routeCallback->bindto ($this, __class__);    }    Public Function Dispatch ($currentPath) {        foreach ($this->routes as $routePath = + $callback) {            if ($ callback = = = $currentPath) {                $callback ();            }        }        Header (' http/1.1 '. $this->responsestatus);        Header (' Content-type: '. $this->responsecontenttype);        Header (' Content-length: '. Mb_strlen ($this->responsebody));        echo $this->responsebody;    }}

Here we need to focus on the Addroute method, the parameters of this method are a route path and a route callback, the parameters of the dispatch method is the path of the current HTTP request, it will call the matching route callback. Line 9th is the point where we bind the routing callback to the current instance of the app. Doing so can handle the status of the app instance in the callback function:

$app = new app (); $app->addroute (' User/nonfu ', function () {    $this->responsecontenttype = ' Application/json; Charset=utf8 ';    $this->responsebody = ' {' name ': ' Laravelacademy '} ';}); $app->dispatch (' User/nonfu ');

At the bottom of the larval is also useful to the BindTo method, see Illuminate\support\traits\macroable __call method:

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.