Retrieve the Currently Executing Closure in PHP 8.5

3 months ago 1

PHP 8.5 will support recursion in Closures by fetching the currently executing Closure (hat tip to Alexandre Daubois). As pointed out in the rfc:closure_self_reference RFC, the current workaround is binding a variable reference into a closure:

$fibonacci = function (int $n) use (&$fibonacci) {

if ($n === 0) return 0;

if ($n === 1) return 1;

return $fibonacci($n-1) + $fibonacci($n-2);

};

echo $fibonacci(10). "\n";

Starting in PHP 8.5, you can use the getCurrent() method to fetch the currently executing closure. The code takes a different approach from the original RFC mentioned above—the author dubbed the merged proposal as "a much simpler alternative":

$fibonacci = function (int $n) {

if (0 === $n || 1 === $n) {

return $n;

}

$fn = Closure::getCurrent();

return $fn($n - 1) + $fn($n - 2);

};

echo $fibonacci(10) . "\n";

If you're interested in the implementation, check out Pull Request #18167 in the PHP source (see eb65ec4).

Read Entire Article