Re: Closure::getCurrent() for recursion
On 15 April 2025 00:01:18 BST, Krinkle <[email protected]> wrote:
>Eg:
>
>$a = function ($a) {
> $aFn = Closure::current(...);
> $aFn(4) === Closure::current(4);
>};
I think there's some confusion on this thread; as I understand it, the proposal is not for a
magic function to *call* the current closure, but a way to get a *reference to it*.
So you don't need, or want, the FCC syntax here - that would create a closure which, whenever
invoked, executes the static method "current" on class "Closure".
What you want is to call the Closure::current (or getCurrent) method directly, which will give you
the existing closure, known as $a in the outer scope. Once you have a reference to it, you can pass
it around and execute it wherever you want.
$aOutside = function (int $foo) use (&$aOutside) {
// Points to the same object as if you used by-ref
assert($aOutside === Closure::getCurrent());
// Store it wherever you like
$aInside = Closure::getCurrent();
assert($aInside === $aOutside);
// Call it like you would any callable
$aOutside(42);
$aInside(42);
Closure::getCurrent()(42); // note the two sets of parens
// Capture it into another closure
$bOutside = function() use ($aInside) {
// Get a self-reference in that one too
$bInside = Closure::getCurrent();
// Do whatever you like with $aInside and $bInside
};
};
Rowan Tommins
[IMSoP]
Thread (15 messages)