array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'en', ), 'this' => array ( 0 => 'closure.getcurrent.php', 1 => 'Closure::getCurrent', 2 => 'Returns the currently executing closure', ), 'up' => array ( 0 => 'class.closure.php', 1 => 'Closure', ), 'prev' => array ( 0 => 'closure.fromcallable.php', 1 => 'Closure::fromCallable', ), 'next' => array ( 0 => 'class.stdclass.php', 1 => 'stdClass', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'language/predefined/closure/getcurrent.xml', ), 'history' => array ( ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); contributors($setup); ?>
(PHP 8 >= 8.5.0)
Closure::getCurrent — Returns the currently executing closure
Returns the currently executing closure. This method is primarily useful
for implementing recursive closures without needing to capture a reference
to the closure variable using the use keyword.
This method must be called from within a closure; calling it outside of a closure context will result in an error.
This function has no parameters.
Returns the currently executing Closure instance.
Throws an Error if called outside of a closure context.
Example #1 Closure::getCurrent() example
Using Closure::getCurrent() to implement a recursive Fibonacci function:
<?php
$fibonacci = function (int $n) {
if (0 === $n || 1 === $n) {
return $n;
}
$fn = Closure::getCurrent();
return $fn($n - 1) + $fn($n - 2);
};
echo $fibonacci(10); // Outputs: 55
?>Example #2 Comparison with traditional approach
Prior to PHP 8.5, implementing recursive closures required capturing a reference
to the closure variable using the use keyword:
<?php
// Traditional approach (still works in PHP 8.5)
$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); // Outputs: 55
?>
The Closure::getCurrent() approach eliminates the need to
declare the variable with a reference in the use clause,
making the code cleaner and less error-prone.