A brief analysis of the closure and anonymous function interpretation in PHP

Source: Internet
Author: User
Tags php class sprintf
PHP closures and anonymous functions use the same syntax as normal functions, but closures and anonymous functions are actually objects disguised as functions (instances of the closure class). The following is to introduce the closure of PHP and anonymous function knowledge, need to refer to the friend

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

An anonymous function is a function that has no name. Anonymous functions can be assigned to variables and can be passed like any other PHP object. However, the anonymous function is still a function, so it can be called and passed in parameters. Anonymous functions are particularly well-suited as callbacks for functions or methods.

Note: In theory, closures and anonymous functions are different concepts. However, PHP sees it as the same concept. Therefore, when we refer to closures, we refer to anonymous functions and vice versa.

PHP closures and anonymous functions use the same syntax as normal functions, but closures and anonymous functions are actually objects disguised as functions (instances of the closure class).

Creating closures

$closure = function ($name) {  return sprintf ("Hello%s", $name);} Echo $closure ("Jerry");//detects if the $closure variable is a closure var_dump ($closure instanceof closure);

The above code creates a closure object and assigns it to the $closure variable. Closures are similar to normal PHP functions, using the same syntax, receiving parameters, and returning values.

Description: We were able to invoke the $closure variable because the value of the variable is a closure, and the closure object implements the __invoke () Magic method. As long as the variable name is followed by (), PHP will find and invoke the __invoke() method.

Using closures

We usually use PHP closures as callbacks for functions and methods. Many PHP functions use callback functions, such as array_map() and preg_replace_callback() . The following example, we will use ARRAY_MAP () to process the array, each item of the array is increased by 1:

$nubmers = Array_map (function ($number) {  return $number + +;}, [Var_dump]); ($numbers);

Attach Status

PHP closures do not automatically encapsulate the state of the application like a real javascrypt closure, and we must manually invoke the BindTo () method of the closure object or use the Using keyword to attach the state to the PHP closure.

Using the USE keyword

Using the Use keyword to attach a closure state is more common, so let's look at this way first. When you attach a variable to a closed package by using the Use keyword, the attached variable remembers the value assigned to it when attached.

function Car ($name) {  return function ($statu) use ($name) {    return sprintf (' Car%s is%s ', $name, $statu);}   } The car name is encapsulated in the closure $car = car ("BMW");//The action of the call car//output--"BMW is Running" Echo $car ("Running");

Note: Using the USE keyword allows you to pass multiple parameters into a closure, which is to use commas to separate multiple parameters, just like the parameters of a PHP function or method.

Use the BindTo () method to attach the state of a closure

Similar to other PHP objects, each closure instance can use the $this keyword to get the internal state of the closure. The default state of a closure object is useless, but there is a __invoke () Magic Method and a BindTo () method.

The BindTo () method adds some interesting potential to closures. We can use this method to bind the internal state of the Closure object to other objects.

The second parameter of the BindTo () method is important to specify the PHP class to which the object that binds the closure belongs. Therefore, closures can access protected and private member variables in the object that binds the closure.

Class testclosure{  private $name =[];  Private $age;  Private $sex;  Public Function Addperson ($name, $personCallback) {    //binds the closure object to the current instance    $this->name[$name] = $personCallback- >bindto ($this, __class__);  }  Public function display ($name) {    foreach ($this->name as $key = + $callback) {      if ($key = = $name) {        // Executes the closure object, attaching the closure state to the class        $callback ();      }    }    echo "Name: {$name}\n";    echo "Age: {$this->age}\n";    echo "Sex: {$this->sex}\n";  }} $person = new Testclosure (); $person->addperson ("Jerry", function () {  $this->age = +;  $this->sex = "Man";}); $person->display ("Jerry");/** outputname:jerryage:19sex:man*/

Summarize

The above is a small part of the PHP to introduce the closure and anonymous functions, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for the support of PHP Chinese network!

Articles you may be interested in:

Source Analysis Laravel The reason for repeating the same queue task

About Laravel Redis Multi-process simultaneous fetch queue problem explanation

PHP-MSF source of the detailed


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.