Can PHP Functions Be Recursively Anonymous?
In PHP, the possibility of creating a function that is both recursive and anonymous has perplexed programmers. This question arises due to the typical use of function names for recursion. However, as the provided example demonstrates, a recursive anonymous function can indeed be implemented in PHP.
The provided code, attempting to calculate the factorial of a number using recursion within an anonymous function, faces a challenge when passing in the function name. To resolve this, it's crucial to pass the function as a reference. By adding an ampersand (&) before $factorial in the use statement, the function itself becomes available within the anonymous function.
Here's the modified code:
<code class="php">$factorial = function( $n ) use ( &$factorial ) { if( $n == 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 );</code>
With this modification, the function $factorial can now reference itself in a recursive manner, allowing the desired factorial calculation to function correctly.
The above is the detailed content of ## Can PHP Functions Be Recursively Anonymous? A Deep Dive into Function References and Recursion.. For more information, please follow other related articles on the PHP Chinese website!