On 04.10.20 22:08, Rowan Tommins wrote:
If we added an opt-in syntax for "capture everything", we might
instead write this:

$f = function() use (*) {
     $x = $y = $z = null;
}

Without re-initialising all local variables, we would no longer be
able to know if they were actually local without looking at the
surrounding scope for a value that might be captured. I am unconvinced
by this trade-off of opt-out instead of opt-in.

One use case I've seen proposed is closures which capture a large
number of variables; I would be interested to see an example where
this is the case and is not a "code smell" in the same way as
requiring a large number of parameters.

Something like "use (*)" seems like a great enhancement to me. I often
use a wrapper function for SQL transactions, something like:

```php
public function update(int $numberId, int $addressId, bool $isMainNumber
= false): void
{
    $this->transaction->run(function () use ($numberId, $addressId,
$isMainNumber): void {
      // Do all SQL queries for the update
    });
}

```

In these cases there is a lot of redundancy because of having to import
the variables, and if a variable is added, it has to be added in two
places in a slightly different way. The following would be much nicer:

```php
public function update(int $numberId, int $addressId, bool $isMainNumber
= false): void
{
    $this->transaction->run(function () use (*): void {
      // Do all SQL queries for the update
    });
}

```

This would also increase code readability.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to