Thanks for this RFC, here are my 2cents:
I think the current syntax is too close to current short closures, and
since it allows multiline closures, it would imply that by default all
multiline short closures are scoped, which is not intuitive since
traditional closures don't capture by default.
Instead, I think replacing thefn () { }syntax to add a keyboard
indicating it inherits the scope would drastically help making it more
intuitive.I would imagine instead something like this:
$externalVar = 0;
$closure1 = scoped fn () => $newVar1 = $externalVar++;
$closure2 = scoped function () {
return $newVar2 = $externalVar++;
};
$closure1();
$closure2();
var_dump($newVar1); // int(0)
var_dump($newVar2); // int(1)
var_dump($externalVar); // int(2)This way, for the first case, the only new information that
scoped
brings is the potential existence of$newVar1after the closure's
execution, and for the second closure, it makes it explicit that all
variables in the closure's body are shared with the parent scope.WDYT?
Le 06/05/2026 à 22:09, Bob Weinand a écrit :
Volker and I drafted a RFC:
https://wiki.php.net/rfc/scope-functions
Please consider it and share your feedback.
I hope it will alleviate pain around some of the most common forms of
Closure usage which is "execute this now as part of the called
function", which currently can require a lot of "use ($variables)".For me the primary use case of use ($capturing) was always "I need
this function later and want to explicitly document what escapes my
function". This, however, required this straightforward usage of
Closures to also document every single usage of a variable. Which is
really not that beneficial at all.Thus the scope functions as proposed will be able to fill that gap in
future.Thank you,
Bob
I agree that the new syntax is too close to current short closures.
I don't think we need a new keyword though, I think the presence of =>
in the function definition should indicate that scope is captured, like
this:
function() => {
// ...
}
To put it another way fn() => foo; would be a syntactically identical
version of function() => {return foo;}