In this paper, we describe the self-invocation (recursive) method of PHP based on the closure implementation function. Share to everyone for your reference, as follows:
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 Closure implementation functions of the self-invocation, that is, the implementation of recursive function closure ($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) {//use parameter is passed $n + + of functions closure function itself ; if ($n < $max) {//recursion point, which is the conditional $counter of recursion . = $n. ' <br/> '; Recursively calls itself $fn ($n, $counter, $max); } return $counter; };/ /Remember here must add '; ' semicolon, no semicolon PHP will error, closure function/ * * Here the return value of the function closure is the anonymous function that calls the closure * and the closure function, referring to the closure function passed in Parameters * / 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 above is PHP based on the closure of the implementation function of the self-invocation (recursive) instance analysis of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!