New features of modern PHP series (5) -- closures and anonymous functions

Source: Internet
Author: User
New features of modern PHP series (5) -- closures and anonymous functions 1. Overview

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

A closure is a function that encapsulates the surrounding state during creation. even if the environment where the closure is located does not exist, the state encapsulated in the closure still exists.

An anonymous function is actually a function without a name. an anonymous function can be assigned to a variable and passed like any other PHP function object. However, anonymous functions are still functions, so they can be called and passed in parameters, which is suitable for callback of functions or methods.

Note: In theory, closures and anonymous functions are different, but PHP regards them as the same concept (anonymous functions are also called closure functions in PHP ), so the closure mentioned below refers to anonymous functions, and vice versa.

2. create a closure

Creating a closure is simple:

     

Result printing:

Hello LaravelAcademy.org

Closures are similar to common PHP functions: common syntaxes are the same, parameters are also accepted, and return values can be returned. However, the closure does not have a function name.

Note: The reason why we can call the $ greet variable is that the value of this variable is a closure, and the closure object implements the _ invoke () magic method, as long as there is () after the variable name (), PHP will find and call the _ invoke method.

We usually use the PHP closure as the callback method of the function. In fact, many PHP functions use the closure, such as array_map and preg_replace_callback. this is an excellent time to use the PHP anonymous function. Remember, closures are the same as other values and can be passed into other PHP functions as parameters:

      

To implement such a function before the closure appears, a PHP developer can only create a named function separately and then reference the function by name:

       

In this way, the implementation of callback and the place of use are isolated, and the code using closures is more concise.

3. inherit variables from the parent scope

In PHP, you must manually call the bindTo method of the closure object or use the use keyword to append the variables and states of the parent scope to the PHP closure. In practical applications, most of them are implemented using the use keyword.

Use keywords

In fact, the Laravel framework also uses a lot of closures, the most common such as routing definition:

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

Both functions are closures. The application scenario of inheriting variables from the parent scope is also prone in the underlying Laravel source code, such as the saveOrFail method of Model. php (Illuminate \ Database \ Eloquent:

The function of this method is to use transactions to save model data to the database, where we use closures to return the Save status, at the same time, use the use keyword to pass the $ options of the parent scope to the closure so that it can access the data.

In addition, multiple parent scope variables can be passed to the closure, such as the forceFill method in the Model class:

Multiple variables can be separated by commas.

BindTo method

As we have mentioned earlier, closure is an object, so we can use the $ this keyword in the closure to obtain the internal state of the closure. the default state of the closure object is useless, note the _ invoke magic method and bindTo method.

The function of _ invoke has been mentioned earlier. When an object is called by calling a function, the _ invoke () method is automatically called.

Next, let's take a look at the bindTo method. through this method, we can bind the internal state of the closure to other objects. Here, the second parameter of the bindTo method is particularly important. its function is to specify the PHP class of the object to which the closure is bound, the closure can access the protected and private member variables in the objects of the Federated closure elsewhere.

You will find that the PHP framework often uses the bindTo method to map the routing URL to the anonymous callback function. The framework will bind the anonymous callback function to the application object, in this way, the $ this keyword can be used in anonymous functions to reference important application objects:

    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 are the path of the current HTTP request, it will call the matching route callback. Row 9th is the focus. we bind the route callback to the current App instance. In this way, the App instance status can be processed 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');

The bindTo method is also used at the bottom layer of Larval. for details, see The _ call method of Illuminate \ Support \ Traits \ Macroable:

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.