Closure::getCurrent
Closure::getCurrent
Returns the currently executing closure
Closure **Closure::getCurrent**
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 keyword.
use
This method must be called from within a closure; calling it outside of a
closure context will result in
Error: Current function is not a closure.
Returns the currently executing instance.
Closure
Throws an if called outside of a closure
context.
Error
Voorbeeld: example
Using to implement a
recursive Fibonacci function:
Closure::getCurrent
<?php
$fibonacci = function (int $n) {
if ($n === 0 || $n === 1) {
return $n;
}
$fn = Closure::getCurrent();
return $fn($n - 1) + $fn($n - 2);
};
echo $fibonacci(10); // Outputs: 55
?>
Voorbeeld: Comparison with traditional approach
Prior to PHP 8.5, implementing recursive closures required capturing a reference
to the closure variable using the keyword:
use
<?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 approach eliminates the need to
declare the variable with a reference in the clause,
making the code cleaner and less error-prone.
Closure::getCurrent``use