> 2. Support block expressions as a language-level concept, analogous to
> https://doc.rust-lang.org/reference/expressions/block-expr.html

This is my personal preference. As I mentioned in chat, if we go this
route, there is a notable pain point: in "short" closures which have
blocks, how do you capture by reference if needed?

Consider this situation:

    // function array_push(array &$array, mixed ...$values): int;
    $array = [];
    $value = fn ($x) => array_push($array, $x);

I have an incomplete idea about allowing `&` at the call-site if and
only if the corresponding parameter is taken by reference:

    // Ok, $array is taken by reference in array_push
    $value = fn ($x) => array_push(&$array, $x);

    // Not ok, ...$values are not taken by reference in array_push
    $key = '';
    $value = fn ($x) => array_push(&$array, &$key, $x);

Then, when `&` is given at the call-site, that variable is captured by
reference. If they don't want it to be captured by-reference, then
they have choices:

    // Choice 1: omit the `&` at the call-site.
    $value = fn ($x) => array_push($array, $x);

    // Choice 2: copy the array.
    // Assumes blocks are allowed.
    $value = fn ($x) => {
        $copied = $array;
        array_push(&$copied, $x);
    }

It would still be valid to omit `&` at the call-site in PHP 8.x so a
transition can be made. Theoretically, we could make it required in
PHP 9.0 or 10.0.

Nikita started an RFC for this 5 years ago:
https://externals.io/message/101254

I do not know exactly why it was not voted on. There was substantial
drama in the discussion that was, in my opinion at least, not really
relevant to the RFC contents.

The original motivations still stand:
 1. The code becomes more readable by humans.
 2. The code becomes more readable by analyzers and optimizers.

And now we have another reason:
 3. Enables auto-capture by-reference when it is necessary.

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

Reply via email to