This article describes php self-calling (recursion) methods for implementing functions based on closures. For your reference, the php closure may not be commonly used, but in some cases, you can still consider using php closure to implement some functions, such as recursion, here we will introduce how to implement recursive php closures using php closures to implement function self-calls, that is, implement recursive functionclosure ($ n, $ cou this article describes php self-calling (recursion) methods for implementing functions based on closures. We will share this with you for your reference. The details are as follows:
Php closures may not be commonly used, but in some cases, you can still consider using php closures to implement certain functions, such as Recursion. here we will introduce how to implement recursion using php closures.
// Php closures implement function self-calls, that is, implementing recursive function closure ($ n, $ counter, $ max) {// Anonymous function, here, the parameter addition & symbol of the function is that the cited call parameter itself $ fn = function (& $ n, & $ counter, & $ max = 1) use (& $ fn) {// The use parameter passes $ n ++ of the function closure function itself; if ($ n <$ max) {// recursive point, that is, the recursive condition $ counter. = $ n.'
'; // Recursively call your own $ fn ($ n, $ counter, $ max) ;}return $ counter ;}; // Remember to add '';'' semicolon, php reports an error when no extra points are added. The closure function/** here, the closure function returns a value that calls the closure's anonymous function * and the closure function, reference the parameter */return $ fn ($ n, $ counter, $ max) passed in by the closure function;} echo (closure (0, '', 10 ));
This is a simple function that uses php closures to implement recursion. In fact, if we modify this function a little bit, we can implement many functions, such as Infinitus classification.
For the closure functions, we do not need to reference the closure parameter. we can set the closure function parameters in closure.
We do not need to return the value of the closure function, because the closure function is in the closure function, we can set the variable in closure to pass to the closure function, and then, recursively retrieve what we want using closures stored in arrays, and use the closure function to return what the closure function gets. Therefore, the closure function can return no value, the key is what you want to get.
In short, you only need to use this closure function to implement what you need and then return what you need. it is not necessarily necessary to obtain from the return value of the closure function.
The above is the content of php self-calling (recursive) instance analysis based on closures to implement functions. For more information, see PHP Chinese website (www.php1.cn )!