Implementing Anonymous Recursive Functions in PHP
When embarking on the task of crafting recursive functions in PHP, one might aspire to shroud them with anonymity. However, a pitfall presents itself when attempting to pass the function name as an argument to itself, as demonstrated in the code below.
<code class="php">$factorial = function( $n ) use ( $factorial ) { if( $n <= 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 );</code>
This endeavor will prove futile, leaving you with a lingering question: can PHP functions be both recursive and anonymous?
The answer lies in understanding the mechanics of variable referencing. To establish a recursive connection, the function must hold a reference to itself. This can be achieved by passing the function as a reference using the '&' operator. Below is an example of how this modification can unblock the anonymous recursion:
<code class="php">$factorial = function( $n ) use ( &$factorial ) { if( $n == 1 ) return 1; return $factorial( $n - 1 ) * $n; }; print $factorial( 5 );</code>
With this adjustment in place, the PHP function transcends the boundaries of anonymity and seamlessly wields its recursive powers.
The above is the detailed content of ## Can PHP Functions Be Both Recursive and Anonymous?. For more information, please follow other related articles on the PHP Chinese website!