PHP closures may not be common, but in some cases it is possible to consider using PHP closures to implement certain functions, such as recursion, which is the recursive implementation of PHP closures
//PHP closures Implement the self-invocation of functions, that is, to implement recursionfunctionClosure$n,$counter,$max){ //anonymous function, here the function of the parameter plus & symbol is, the address of the call parameter itself $FN=function(&$n,&$counter,&$max=1) Use(&$FN){//The use parameter passes the function closure function itself $n++; if($n<$max){//Recursive point, which is the condition of recursion $counter.=$n.‘ <br/> '; //Call yourself recursively $FN($n,$counter,$max); } return $counter; };//Remember that there must be a ";" semicolon, no semicolon PHP will error, closure function /** The return value of the function closure is the anonymous function that calls the closure * and the closure function, which refers to the parameters passed in by the closure function .*/ return $FN($n,$counter,$max); }Echo(Closure (0, ', 10));
This is a simple function that uses PHP closures to implement recursion, in fact, if we modify this function slightly, we can achieve a lot of functions, for example, infinite pole classification.
On the inside of the closure function, in fact, we can also not reference the outside of the closure parameter, the inside of the parameters of the closure function, we can set in the internal closure.
We can also not return the value of the closure function, because the closure function is inside the closure function, we can set a variable inside the closure to pass to the closure function, and then, with the closure of the recursion to get what we want to store in the array, Then use the closure function to return what the closure function gets, so the closure function can also have no return value, the key is what you want to get.
In short, you just use this closure function to implement what you want, and then return what you need, not necessarily from the return value of the closure function.
The self-invocation of the PHP closure implementation function is also recursive