On 28/04/2021 15:31, Nikita Popov wrote:
My suggestion would be to allow use(&$count) on fn(), which allows capturing
certain variables by reference rather than by value.
It might be rather confusing for the use block to sometimes mean
"capture exactly these variables", and sometimes mean "capture all
variables, but modify *how* you capture these ones", based on if it
follows "function" or "fn".
In other words, it's not obvious at a glance that these two closures
have completely different effects, and why:
$increment = 1;
$count = 0;
$a = function() use (&$count) { $count += $increment; }
$b = fn() use (&$count) { $count += $increment; }
I think that extensive experience in other programming languages has shown
that auto-capture does not hinder readability of code, and I don't see any
particular reason why the effects in PHP would be different.
The difference between PHP and a lot of those other languages is that
variables are not imported automatically from other scopes.
In PHP, the following global function and closure would not use the same
definition of $foo:
$foo = 42;
function echoFoo { echo $foo; }
$echoFoo = fn() { echo $foo; }
That's not automatically a bad thing, but it is an extra concern that
PHP has which other languages don't.
Regards,
--
Rowan Tommins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php