Recursion in PHP
Our example demonstrates recursive functions in PHP. Here’s a classic example of recursion:
To run the program, save it as recursion.php
and use the PHP interpreter:
In this example, we define two recursive functions:
- A traditional named function
fact
that calculates the factorial of a number. - An anonymous function stored in the variable
$fib
that calculates the Fibonacci sequence.
The fact
function is straightforward recursion. It calls itself with n-1
until it reaches the base case of n == 0
.
For the Fibonacci function, we use an anonymous function (closure). In PHP, to make a closure recursive, we need to use the use
keyword with a reference to the variable holding the function (&$fib
). This allows the function to call itself.
Both functions demonstrate how recursion can be used to solve problems that have a recursive nature, such as factorial calculation and the Fibonacci sequence.