An explanation of anonymous and closure functions in PHP

Source: Internet
Author: User

This article to share the content is to explain the PHP anonymous function and closure function, has a certain reference value, the need for friends can refer to

Anonymous functions and Closure functions for PHP


Introduction: Anonymous functions and closure functions are not particularly advanced knowledge, but many of the newly-introduced friends are always very confused, because people are accustomed to write the function is used to invoke, anonymous function and closure function what to do?

anonymous functions

The official PHP explanation is as follows:
The anonymous function (Anonymous functions), also called the closure function (closures), allows temporary creation of a function without a specified name. The value most often used as the callback function (callback) parameter. Of course, there are other applications as well.

This is very simple, can be used as a callback function, the following example is the callback function

<?phpecho preg_replace_callback (' ~-([A-z]) ~ ', function ($match) {    return Strtoupper ($match [1]);}, ' Hello-world ');//Output helloworld?>

In the above example, thepreg_replace_callback function requires three parameters, the first parameter is a regular expression to match the data, the second argument is a function, the third argument is a string that needs to be matched, or it can be written like this

<?php$testfunc = function ($match) {        return Strtoupper ($match [1]);    };  echo Preg_replace_callback (' ~-([A-z]) ~ ', $testFunc, ' Hello-world '); Output HelloWorld?>

But we see this method obviously we only need to use once, so there is no need to give him a name, and there is no need to assign him to a variable (the process of assigning a value to a variable: PHP will automatically convert this expression into a built-in class Closure object instance assignment to the variable)

Closure function

The anonymous function in PHP is also called a closure function, so there is no difference. But the concept of closure in general is not the case, let us first talk about the traditional closure, and provide an article in JS in the closure for the closure in PHP (anonymous function) comparison.
Learn JavaScript closures (Closure)-Nanyi

There is no traditional closure function in PHP, because functions in PHP cannot invoke variables in the scope of the husband. As follows

<?php    function A () {        $a = one;                Function B () {            $b =;                        echo $a;                        echo $b;        }        b ();    }    A ();    Reported notice:undefined variable:a in index.php on line 6    //22    ?>

and read the above article learned that JS is possible. Therefore, the anonymous function in PHP is also called the closure function, you can also pass the parent scope of the variable into the closure function (to achieve the same effect as JS gets the parent scope variable), PHP uses the USE keyword, as follows

<?php$count = 0; $a = function () {var_dump ($count);}; $b = function () use ($count) {var_dump ($count);}; $count + +; $c = function () use (& $count) {var_dump ($count);}; $count + +; $a ();    Null   notice:undefined Variable:count in$b ();    int 0$c ();    int 2$count++; $b ();    int 0?>

The output of the above example is not the same as what you think.

parsing : The closure function (anonymous function) uses use to get the side-effect domain variable when the function is defined, regardless of when it is called. If you want to get the variable value at the time of the call, you need to pass it by reference. How to use it depends on the use of the scene.

Several common scenarios are listed.

    1. as a callback function

      // One of the examples we used <?php/* * recipes after splitting a meal * parameters cannot be empty * */public function mergefoodsstr ($str, array $mapping) {//$str = ' cabbage half tree , __2__ abalone mushrooms Two, __0__ a root, __1__ two, the proportion of the three is 100:100:15, soy sauce 5 grams, sesame oil 2 grams, salt 1 grams.  ';//$mapping = Array (//0 =>array (' name ' = ' carrot ', ' id ' = ' bayi '),//1 =>array (    ' Name ' = ' radish ', ' id ' = ' (') ', '//' 2 =>array (' name ' = ' apricot ', ' id ' = ' 1841 ')//);    if (Empty ($str) | | empty ($mapping)) {return false; } $strNew = Preg_replace_callback (' "|__ (\d) __|"    ', function ($matches) use ($mapping) {return $mapping [$matches [1]][' name '];    }, $STR);    $this->log (' string of ingredients after stitching ', $strNew); return $strNew;}? 
    2. If you are using a one-time function that cannot be reused, you can use the closure function

    3. Using Array_work () function with anonymous function to reduce the number of foreach layers

    4. And so on

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.