Re: Closure::getCurrent() for recursion

From: Date: Mon, 14 Apr 2025 23:01:18 +0000
Subject: Re: Closure::getCurrent() for recursion
References: 1 2  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Mon, 31 Mar 2025, Jorg Sowa wrote:
> I thought about edge cases and what the desired output is with nested closures?
> 
> Example:
> <?
> $a = function (int $numberA) {
>     $b = function (int $numberB) {
>         if($numberB < 10) {
>             return Closure::current(10);
>         }
>         return $numberB;
>     };
>     return $b($numberA) + $numberA;
> };
> 
> var_dump($a(4));

I'd expect it to refer to current/local/nearest function.

If you wanted a way to call $a from inside $b, I'd expect callable syntax to be able to capture
these in-place.

Eg:
 
$a = function ($a) {
  $aFn = Closure::current(...);
  $aFn(4) === Closure::current(4);
};

https://www.php.net/manual/en/functions.first_class_callable_syntax.php

This could be use'd to a nested $b function, or otherwise passed/returned to other functions
without changing meaning.

That is, I would not expect it to behave like late-static binding where it'll always be for the
"current" fn that's invoking it, but rather capture where the callable expression
happened.

--
Timo Tijhof,
Wikimedia Foundation.
https://timotijhof.net/




Thread (15 messages)

« previous php.internals (#127109) next »