Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Recursive Closure

<?php

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

print factorial( 5 );

?>

To make a recursive closure, the closure must be both stored in a variable and passed as a use parameter to the same factorial.

It also works for arrow functions, although there is no the use, but the variable must be defined first, so it can be used in context later.

See Also

PHP Features

Last updated: 10 September 2026