Detailed explanation of anonymous functions and closure functions in PHP

零到壹度
Release: 2023-03-23 16:00:02
Original
2999 people have browsed it

The content of this article is to share with you a detailed explanation of anonymous functions and closure functions in PHP. It has a certain reference value. Friends in need can refer to

PHP’s Anonymous Functions and closure functions


#tags: Anonymous function closure function php closure function php anonymous function function use


##Introduction: Anonymous functions and closure functions are not particularly advanced knowledge, but many friends who are just getting started are always confused, because everyone is accustomed to writing functions just for calling them. What are anonymous functions and closure functions used for?

Anonymous functions

php official explanation is as follows:

Anonymous functions (Anonymous functions), also called closure functions (closures), allow temporary creation of a function without a specified name . The value most commonly used as a callback function argument. Of course, there are other applications as well.

What is said here is very simple, it can be used as a callback function. The following example is the

<?php
echo preg_replace_callback(&#39;~-([a-z])~&#39;, function ($match) {
    return strtoupper($match[1]);
}, &#39;hello-world&#39;);
// 输出 helloWorld
?>
Copy after login
used as a callback function

In the above example, the

preg_replace_callback function It requires three parameters. The first parameter is a regular expression used to match data, the second parameter is a function, and the third parameter is the string that needs to be matched. You can also write it like the following

<?php
$testFunc = function ($match) {
        return strtoupper($match[1]);
    };
 
 echo preg_replace_callback(&#39;~-([a-z])~&#39;, $testFunc, &#39;hello-world&#39;);
 // 输出 helloWorld
 ?>
Copy after login

But we see that we only need to use this method once, so there is no need to name it again, and there is no need to assign it to a variable (the process of assigning values ​​to variables: PHP will automatically Convert it into an object instance of the built-in class Closure and assign it to a 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 the general sense is not like this. Let's first talk about closure in the traditional sense, and provide an article to compare closures in js with closures (anonymous functions) in php.

Learn Javascript closure (Closure) - Ruan Yifeng

There is actually no closure function in the traditional sense in PHP, because functions in PHP cannot call variables in the scope. As shown below

<?php
    function a(){
        $a = 11;        
        function b(){
            $b = 22;            
            echo $a;            
            echo $b;
        }
        b();
    }
    a();
    //报Notice:Undefined variable: a in index.php on line 6
    //22
    ?>
Copy after login

Looking at the above article, we know that it is possible in js. Therefore, anonymous functions in PHP are also called closure functions. You can also pass variables from the parent scope into the closure function (achieving an effect similar to js obtaining parent scope variables). The use keyword is used in PHP, 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

?>
Copy after login

Is the output of the above example different from what you think?

Analysis: The closure function (anonymous function) uses use to obtain the side effect domain variable when the function is defined, no matter when it is called. If you want to get the variable value when calling, you need to pass it by reference. How to use it depends on the usage scenario.

Lists several common scenarios

  1. As a callback function

    //一个我们使用过的例子
    <?php/*
     * 菜谱拆分食物后的拼接
     * 参数均不能为空
     * */public function mergeFoodsStr($str,array $mapping){
     //        $str = &#39;白菜半棵、__2__鲍菇两只、__0__一根,__1__两根,三者比例为100:100:15,酱油5克,香油2克,盐1克。&#39;;//        $mapping = array(//            0 =>array(&#39;name&#39; => &#39;胡萝卜&#39;,&#39;id&#39; =>  &#39;81&#39; ),//            1 =>array ( &#39;name&#39; => &#39;萝卜&#39;, &#39;id&#39; =>  &#39;72&#39;),//            2 =>array ( &#39;name&#39; =>  &#39;杏&#39;, &#39;id&#39; => &#39;1841&#39;)//        );
        if(empty($str) || empty($mapping)){        return false;
        }    $strNew = preg_replace_callback(&#39;"|__(\d)__|" &#39;,function ($matches) use ($mapping){
            return $mapping[$matches[1]][&#39;name&#39;];
        },$str);    $this->log(&#39;拼接后的食材字符串&#39;,$strNew);    return $strNew;
    }?>
    Copy after login

  2. ## If it is a one-time use function that cannot be reused, you can use the closure function

  3. Use the array_work() function with the anonymous function to reduce the number of foreach layers
  4. etc
  5. The above is the detailed content of Detailed explanation of anonymous functions and closure functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!