Home  >  Article  >  Backend Development  >  How to Create Recursive Anonymous Functions in PHP?

How to Create Recursive Anonymous Functions in PHP?

DDD
DDDOriginal
2024-10-25 07:55:28351browse

How to Create Recursive Anonymous Functions in PHP?

Creating Recursive Anonymous PHP Functions

It can be advantageous to create anonymous functions that are recursive in PHP. The code below demonstrates how to accomplish this, passing a function as a reference.

$factorial = function( $n ) use ( &$factorial ) {
    if( $n == 1 ) return 1;
    return $factorial( $n - 1 ) * $n;
};
print $factorial( 5 );

The above is the detailed content of How to Create Recursive Anonymous Functions in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn