Re: [RFC] Auto-capture multi-line closures and short functions take 2

From: Date: Wed, 28 Apr 2021 16:16:26 +0000
Subject: Re: [RFC] Auto-capture multi-line closures and short functions take 2
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-114242@lists.php.net to get a copy of this message
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]

Thread (76 messages)

« previous php.internals (#114242) next »