Home > Article > Backend Development > Anonymous functions and closure usage in php
This article mainly introduces the usage of anonymous functions and closures in php. Interested friends can refer to it. I hope it will be helpful to everyone.
1: Anonymous functions (can only be used in php5.3.0 or above)
Anonymous functions (Anonymous functions) in php, also called Closure function (closures) allows specifying a function without a name. The most commonly used one is the parameter value of the callback function. (http://php.net/manual/zh/functions.anonymous.php)
Definition of anonymous function:
$closureFunc = function(){ .... };
eg : Assign the anonymous function to a variable and call it through the variable
$closureFunc = function($str){ echo $str; }; $closureFunc("hello world!");
Output: hello world !
2: Closure
2.1 Put the anonymous function in the ordinary function, you can also put the anonymous function Return, this constitutes a simple closure
function closureFunc1(){ $func = function(){ echo "hello"; }; $func(); } closureFunc1();//输出: hello
##2.2 Reference local variables in anonymous functions
function closureFunc2(){ $num = 1; $func = function(){ echo $num; }; $func(); } closureFunc2();//Notice: Undefined variable: num
function closureFunc2(){ $num = 1; $func = function() use($num){ echo $num; }; $func(); } closureFunc2();//输出: 1
2.3 返回匿名函数
function closureFunc3(){ $num = 1; $func = function() use($num){ echo $num; }; return $func; }$func = closureFunc3(); //函数返回匿名函数$func(); //然后我们在用$func() 调用//输出: 1
2.4 当我们在返回匿名函数时候怎么给匿名函数传参呢? 其实跟普通函数传参数一样
function closureFunc4(){ $num = 1; $func = function($str) use($num){ echo $num; echo "\n"; echo $str; }; return $func; }$func = closureFunc4();$func("hello, closure4");//输出: //1 //hello, closure4
2.5 怎么用闭包来改变上下文引用的变量值?
function closureFunc5(){ $num = 1; $func = function() use($num) { echo "\n"; $num++; echo $num; }; echo "\n"; echo $num; return $func; }$func = closureFunc5();$func();$func();$func();//输出: // 1 // 2 // 2 // 2
看上面的输入结果,显然没有达到目的, 其实只要加一个 & 引用符号就可以了
function closureFunc5(){ $num = 2; $func = function() use(&$num) { echo "\n"; $num++; echo $num; }; echo "\n"; echo $num; return $func; }$func = closureFunc5();$func();$func();$func();//输出: // 2 // 3 // 4 // 5
2.6 把匿名函数当作参数传递
function callFunc($func){ $func("argv"); } callFunc(function($str){ echo $str; })//输出: // argv
The above is the detailed content of Anonymous functions and closure usage in php. For more information, please follow other related articles on the PHP Chinese website!