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

- Thread: https://externals.io/message/113740
- Original archive: https://news-web.php.net/php.internals/113740
- Started by Larry Garfield on 2021-03-24T16:19:58+00:00
- Messages: 74
- RFC: Short Closures 2.0 (Declined) — https://externals.io/rfc/auto-capture-closure.md
- RFC: Short functions (Declined) — https://externals.io/rfc/short-functions.md
- Page 1 of 3: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/113740.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #113740 — Larry Garfield — 2021-03-24T16:19:58+00:00

URL: https://externals.io/message/113740#113740

Greetings, Internalians.

Some months back I proposed an RFC for short functions.

https://wiki.php.net/rfc/short-functions

After some discussion, I put it on hold to ensure that it was compatible with the other discussion floating about around an alternate syntax for multi-line closures that did auto-capture.  It's important that the syntax of both proposals is consistent.

Nuno Maduro and i have talked recently and worked out the syntax that is consistent between both proposals.  That takes 'fn' off the table for short-functions, for reasons discussed in both RFCs.

To that end, I offer:

1) The updated short-functions RFC: https://wiki.php.net/rfc/short-functions

2) A new RFC, code by Nuno, for auto-capturing multi-statement closures: https://wiki.php.net/rfc/auto-capture-closure

These are separate RFCs and at this time we plan to send them to separate votes, but I list them together to demonstrate that they have been developed in a mutually-compatible way.

Further details in the auto-capture-closure RFC.

-- 
  Larry Garfield
  larry@garfieldtech.com

---

## #113742 — Nikita Popov — 2021-03-24T17:01:58+00:00

URL: https://externals.io/message/113740#113742 · In reply to: #113740

On Wed, Mar 24, 2021 at 5:20 PM Larry Garfield <larry@garfieldtech.com>
wrote:

> Greetings, Internalians.
>
> Some months back I proposed an RFC for short functions.
>
> https://wiki.php.net/rfc/short-functions
>
> After some discussion, I put it on hold to ensure that it was compatible
> with the other discussion floating about around an alternate syntax for
> multi-line closures that did auto-capture.  It's important that the syntax
> of both proposals is consistent.
>
> Nuno Maduro and i have talked recently and worked out the syntax that is
> consistent between both proposals.  That takes 'fn' off the table for
> short-functions, for reasons discussed in both RFCs.
>
> To that end, I offer:
>
> 1) The updated short-functions RFC:
> https://wiki.php.net/rfc/short-functions
>
> 2) A new RFC, code by Nuno, for auto-capturing multi-statement closures:
> https://wiki.php.net/rfc/auto-capture-closure
>
> These are separate RFCs and at this time we plan to send them to separate
> votes, but I list them together to demonstrate that they have been
> developed in a mutually-compatible way.
>
> Further details in the auto-capture-closure RFC.
>

Could you please create two separate threads for these RFCs?

Nikita

---

## #113743 — Chase Peeler — 2021-03-24T17:15:05+00:00

URL: https://externals.io/message/113740#113743 · In reply to: #113742

> On Wed, Mar 24, 2021 at 5:20 PM Larry Garfield <larry@garfieldtech.com>
> wrote:
>
> > […]
> syntax
> > […]
>
> Could you please create two separate threads for these RFCs?
>
> Nikita
>

I guess my one question would be why we didn't support auto-capture when we
first implemented anonymous functions, and if there was a reason, why does
that no longer apply?


-- 
Chase Peeler
chasepeeler@gmail.com

---

## #113744 — Christian Schneider — 2021-03-24T17:33:54+00:00

URL: https://externals.io/message/113740#113744 · In reply to: #113743

Am 24.03.2021 um 18:15 schrieb Chase Peeler <chasepeeler@gmail.com>:
> I guess my one question would be why we didn't support auto-capture when we
> first implemented anonymous functions, and if there was a reason, why does
> that no longer apply?

My guess would be that it was seen as one of PHP's big strength that variables don't just leak into other contexts but that it has to be done explicitly.

Now with arrow functions both the benefit of auto-capturing is bigger compared to the actual function 'body', it normally only spans a line or two and (for me personally) the absence of {} also kind of make the leakage fit my mental model more easily.

For these reasons I think I lean towards -1 for both https://wiki.php.net/rfc/short-functions <https://wiki.php.net/rfc/short-functions> and https://wiki.php.net/rfc/auto-capture-closure <https://wiki.php.net/rfc/auto-capture-closure> as they add more syntax without (IMHO) a huge benefit.

You might be able to convince me otherwise though ;-)
- Chris

---

## #113745 — Chase Peeler — 2021-03-24T17:38:59+00:00

URL: https://externals.io/message/113740#113745 · In reply to: #113744

On Wed, Mar 24, 2021 at 1:34 PM Christian Schneider <cschneid@cschneid.com>
wrote:

> Am 24.03.2021 um 18:15 schrieb Chase Peeler <chasepeeler@gmail.com>:
> > […]
> we
> > […]
> does
> > […]
>
> My guess would be that it was seen as one of PHP's big strength that
> variables don't just leak into other contexts but that it has to be done
> explicitly.
>
> Now with arrow functions both the benefit of auto-capturing is bigger
> compared to the actual function 'body', it normally only spans a line or
> two and (for me personally) the absence of {} also kind of make the leakage
> fit my mental model more easily.
>
> For these reasons I think I lean towards -1 for both
> https://wiki.php.net/rfc/short-functions <
> https://wiki.php.net/rfc/short-functions> and
> https://wiki.php.net/rfc/auto-capture-closure <
> https://wiki.php.net/rfc/auto-capture-closure> as they add more syntax
> without (IMHO) a huge benefit.
>
> You might be able to convince me otherwise though ;-)
>

I don't really have anything against auto-capture, was just kind of
curious. I guess it is somewhat similar to how x = function(){...} and x =
() => {} work in javascript with respect to "this".

I do think it makes sense to only do auto-capture on the short syntax, so
that you still have the ability to fallback to the long syntax if you don't
want auto-capture, since there are definitely use-cases where it wouldn't
be make sense.
,

> - Chris
>
>

-- 
Chase Peeler
chasepeeler@gmail.com

---

## #113747 — Mark Randall — 2021-03-24T21:26:18+00:00

URL: https://externals.io/message/113740#113747

> As Christian says, automatic capture is a dramatic change to the 
> language's scoping rules, and IMHO requires a more thorough 
> justification on why the current syntax is burdensome. As I've said 
> previously, my naive impression is that a long list of captured 
> variables ought to be as bad a code smell as a long list of parameters; 
> I'm willing to be proven wrong on this, but nobody has yet stepped 
> forward with a real-life example.

Automatic capture ceased to be a dramatic change from PHP the day after 
short closurers were introduced. So they've been a part of PHP for years 
now.

I hit long lists of use() repeatedly, almost always because I need to 
perform a series of operations within a callback, prime examples are 
database transactions and using throw-aware buffering handlers.

In general, anything that needs to wrap a code block in a complex set of 
instructions before and after.

To give my own example, earlier this week I wrote the following:

$x = function () use ($to, $library, $thread, $author, $title, 
$library_name, $top_post) { ... }

That was just to get those variables inside a callback that could be 
invoked inside a throw-aware buffering helper.

I believe that by explicitly stating my intent to use auto capture by 
using fn() { ... } that my code would have been cleaner with less noise.

If I thought otherwise, I would be under no obligation to use them and 
could use function() { ... } instead.

For me auto capture is a solid +1.

Mark Randall

---

## #113748 — Chase Peeler — 2021-03-24T21:45:45+00:00

URL: https://externals.io/message/113740#113748

> 
> > […]
>
> Automatic capture ceased to be a dramatic change from PHP the day after
> short closurers were introduced. So they've been a part of PHP for years
> now.
>
> I hit long lists of use() repeatedly, almost always because I need to
> perform a series of operations within a callback, prime examples are
> database transactions and using throw-aware buffering handlers.
>

DB transaction is one place I have a long list of use parameters as well.
Since the goal is to do as much before we start the transaction as
possible, I always end up with a lot of variables resulting from that prep
work that I need to utilize inside the transaction callback.  My gut tells
me the use-cases for long use lists that don't indicate code smell are
pretty small though.



> In general, anything that needs to wrap a code block in a complex set of
> instructions before and after.
>
> To give my own example, earlier this week I wrote the following:
>
> $x = function () use ($to, $library, $thread, $author, $title,
> $library_name, $top_post) { ... }
>
> That was just to get those variables inside a callback that could be
> invoked inside a throw-aware buffering helper.
>
> I believe that by explicitly stating my intent to use auto capture by
> using fn() { ... } that my code would have been cleaner with less noise.
>
> If I thought otherwise, I would be under no obligation to use them and
> could use function() { ... } instead.
>

I agree. I think as long as we make it clear to users that function() does
not provide auto capture, but fn() does, we're fine. In the same way that
JavaScript make it clear that function(){} changes the meaning of "this"
while () => {} does not. The fact that they behave differently like that is
great in my opinion. I use function(){} when I want the changed context
(like event listener callbacks) and () => {} when I know I only need access
to the parent context and don't care about any possible redefinition.


>
> For me auto capture is a solid +1.
>
> Mark Randall
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

-- 
Chase Peeler
chasepeeler@gmail.com

---

## #113750 — Deleu — 2021-03-24T22:45:44+00:00

URL: https://externals.io/message/113740#113750 · In reply to: #113740

> Greetings, Internalians.
>
> Some months back I proposed an RFC for short functions.
>
> https://wiki.php.net/rfc/short-functions
>
> After some discussion, I put it on hold to ensure that it was compatible
> with the other discussion floating about around an alternate syntax for
> multi-line closures that did auto-capture.  It's important that the syntax
> of both proposals is consistent.
>
> Nuno Maduro and i have talked recently and worked out the syntax that is
> consistent between both proposals.  That takes 'fn' off the table for
> short-functions, for reasons discussed in both RFCs.
>
> To that end, I offer:
>
> 1) The updated short-functions RFC:
> https://wiki.php.net/rfc/short-functions
>
> 2) A new RFC, code by Nuno, for auto-capturing multi-statement closures:
> https://wiki.php.net/rfc/auto-capture-closure
>
> These are separate RFCs and at this time we plan to send them to separate
> votes, but I list them together to demonstrate that they have been
> developed in a mutually-compatible way.
>
> Further details in the auto-capture-closure RFC.
>
> --
>   Larry Garfield
>   larry@garfieldtech.com
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php


These RFC are an amazing addition to PHP. I have been working with PHP 8
for the past few months and small syntax improvements such as short
closure, private constructor promotion, nullsafe operator, etc. are game
changers to my day to day work.

These RFC close some gaps that are natural expectations like short closure
with multiple statements and the ability to simplify even further simple
methods on Data Transfer objects.

I wish the best luck to both RFCs and hope they get approved, if not for
their wonderful merits, maybe at least for the sake of consistent syntax
throughout the language.

---

## #113754 — Mike Schinkel — 2021-03-25T04:12:22+00:00

URL: https://externals.io/message/113740#113754

> 
> 
> 
> > […]
> 
> 
> I strongly disagree. Short closures say "turn this expression into a function". You would have to work really, really hard to introduce a sufficient amount of complexity that scope was hard to follow.

Another perspective is that the short syntax reduces complexity by not needing to be as verbose. 

I just did a search through a few of my codebases and found that I almost never use more than one parameter, but I would still applaud this syntax. Why?

1.) Many of my use-cases for closure functions are within functions with only a few lines that simply return the closure, i.e these functions are names wrappers for the closure to simplify their reuse across the codebase.  Anyway, having to declare the variable twice, once as a function parameter and again in the use() on the next line is just tedious overkill, IMO.  

Then there are a use-cases with `array_filter()` and similar functions where the use() just adds visual complexity to what could otherwise be visually easier to reason about at a glance.

Probably the only use-case I can envision where auto-capture would be problematic would be when you do have really long functions. But if you have really long functions, don't you actually have a different problem that probably needs to be addressed first?

2.) This is subjective, but my workflow frequently has me splitting the screen vertically so I can view two related files side-by-side such as the calling code on one side and the code it calls on the other. For this use-case, I almost always find myself having to scroll horizontally whenever using a closure has a use() so I can see the use() variables. That is tedious and tiring.

So syntax that results in longer lines is problematic for my workflow. I know not everybody can relate but I have to believe that I am not the only one this affects. 

3.) This is also subjective, but because of the requirement for use() I often find myself *not* using a closure because of its visual noise, and the use() is the main contributor to the visual noise. Instead of using `array_filter()` with a side-effect free closure, I use a for loop because it is easier to reason about visually. 

If the short syntax existed I think I would more often use a closure. Maybe I am unique in this, but I am probably not. 

> Full-bodied auto-capture means you can introduce a variable on line 1, and find it's never freed, because it was silently captured by a function on line 200. Since there's no way to declare a local variable, you couldn't even opt *out* of the capture, as "let" or "var" do in JavaScript.

Actually, there is a way to declare a local variable.  Use the long function syntax instead as there is no proposal to deprecate it.

Different syntaxes for different use-cases.

> I hit long lists of use() repeatedly, almost always because I need to perform a series of operations within a callback, prime examples are database transactions and using throw-aware buffering handlers. 
> 
> I think a lot of those use cases are using anonymous functions because they're available, not because they're the best tool for the job.

For some of these use-cases, the auto-capture would be the best tool. 

But if we don't get variable auto-capture then for those use-cases we'd have no choice but to use the tool that is *not* the best tool for the job because it would be the only tool we'd have. 

> A transaction wrapper, for instance, doesn't actually need to pass control to the transaction and back to a callback, it just needs some before and after boilerplate.
> 
> 
> Python has a "with" syntax for this, which calls __enter__ and __exit__ methods on a "Context Manager" object: https://www.python.org/dev/peps/pep-0343/
> 
> Translating the syntax to look more PHP-ish, you'd write something like this:
> 
> with ( new Transaction($db) as $transaction ) {
>     doSomething($to, $library, $thread);
>     andThenSomethingElse($author, $title, $library_name, $top_post);
> }

So "with" is a statement, not an expression?  

Not sure how that helps since I thought one of the benefits of the short function syntax (with variable auto-capture) was to move away from procedural statements and toward more functional expressions?

> The compiler would then insert an appropriate try ... catch ... finally, with no need for a callback, and therefore no need to capture lots of variables. The full internal expansion is quite long, so I've posted it as a gist here: https://gist.github.com/IMSoP/a4e316684415413dca8ec5debf51a812
> 
> This is simpler for the programmer (my example Transaction class is a total of 20 lines long), more efficient at run-time (no extra stack frame for the callback), and possibly even simpler to compile (no analysis needed to work out what variables to capture).
> 
> Obviously, this doesn't cover all cases where automatic capture would be useful, but nor is it just a one-trick pony; the Python spec has lots of example use cases.

It is not clear to me from reading the PEP how a "with" statement obviates the benefit of variable auto-capture? Maybe because I don't "think" in Python, so from reading their examples I cannot see how this relates?

Maybe prepare an RFC proposing a PHP version of the "with" statement and explain in the RFC how it would better address the use-cases of variable auto-capture for closure so we can compare and contrast the potential language additions?  Include examples with variable auto-capture and contrast with your proposed "with" statement?

-Mike

---

## #113756 — Peter Stalman — 2021-03-25T05:36:42+00:00

URL: https://externals.io/message/113740#113756 · In reply to: #113740

On Wed, Mar 24, 2021 at 9:20 AM Larry Garfield <larry@garfieldtech.com>
wrote:

> 1) The updated short-functions RFC:
> https://wiki.php.net/rfc/short-functions
>
> 2) A new RFC, code by Nuno, for auto-capturing multi-statement closures:
> https://wiki.php.net/rfc/auto-capture-closure
>
> These are separate RFCs and at this time we plan to send them to separate
> votes, but I list them together to demonstrate that they have been
> developed in a mutually-compatible way.
>

Hi Larry (and Nuno) ,

Well done on the RFCs and making sure they are compatible and consistent.

That said, I agree with the sentiment that multi-statement auto-capturing
closures can add noise.  It's not just a multi-line `fn()`, as their usage
would be different.  With the single statement and return of `fn()` it was
intended to be used as a function argument where a callback is needed.
There autocapture makes sense to me.

But in the end, it's a matter of preference to use it or not.  I just don't
want PHP to drift closer to the callback hell that is JS.

Looking at the two proposals, I boil it down to this combined example:

```
class Short
{
    public function foo($a, $b, $c): int => match ($a) {
        1, 3, 5 => (fn() {
            $val = $a * $b;
            return $val * $c;
        })(),
        2, 4, 6 => (fn() {
            $val = $a + $b;
            return $val + $c;
        })(),
    };
}

class Long
{
    public function foo($a, $b, $c): int
    {
        return match ($a) {
            1, 3, 5 => self::bar($a, $b, $c),
            2, 4, 6 => self::baz($a, $b, $c),
        };
    }

    private static function bar($a, $b, $c): int
    {
        $val = $a * $b;
        return $val * $c;
    }

    private static function baz($a, $b, $c): int
    {
        $val = $a + $b;
        return $val + $c;
    }
}
```

The Short class is "fine", but I would still prefer the Long class.

Thanks,
Peter

---

## #113757 — Peter Stalman — 2021-03-25T05:43:11+00:00

URL: https://externals.io/message/113740#113757

> To give my own example, earlier this week I wrote the following:
>
> $x = function () use ($to, $library, $thread, $author, $title,
> $library_name, $top_post) { ... }
>
> That was just to get those variables inside a callback that could be
> invoked inside a throw-aware buffering helper.
>

Hi Mark,

Have you considered using an array or DTO to pass the data?

You could also do this (although I'm not advocating it):

```
$vars = `get_defined_vars()`;
$x = function() use ($vars) {
    extract($vars);
    /* ... */
};
```

Thanks,
Peter

---

## #113758 — Peter Stalman — 2021-03-25T05:47:44+00:00

URL: https://externals.io/message/113740#113758 · In reply to: #113743

> I guess my one question would be why we didn't support auto-capture when we
> first implemented anonymous functions, and if there was a reason, why does
> that no longer apply?
>

I believe this was the original discussion:

https://externals.io/message/38290

Thanks,
Peter

---

## #113761 — Rowan Tommins — 2021-03-25T09:28:27+00:00

URL: https://externals.io/message/113740#113761 · In reply to: #113754

> Actually, there is a way to declare a local variable.  Use the long function syntax instead as there is no proposal to deprecate it.

That's not quite what I meant. I meant that you can't say "capture by 
default, but this variable is definitely local".

I'm guessing maybe "$foo = null;" at the top of the function would stop 
it auto-capturing, but the semantics of what exactly gets captured 
aren't spelled out in the RFC. That really needs to be added IMO.


> Instead of using `array_filter()` with a side-effect free closure, I use a for loop because it is easier to reason about visually.


Is that a bad thing? In many cases it's probably more efficient, and 
easier to read.




> It is not clear to me from reading the PEP how a "with" statement obviates the benefit of variable auto-capture? Maybe because I don't "think" in Python, so from reading their examples I cannot see how this relates?


I didn't mean to say that the "with" statement would replace closures in 
general, but it would make them unnecessary *for some specific use 
cases*. You mentioned:

 > prime examples are database transactions and using throw-aware 
buffering handlers.

If your current code looks something like this:

wrap_in_buffer(function($transaction) use ($to, $library, $thread, 
$author, $title, $library_name, $top_post) {
     doSomething($to, $library, $thread);
     andThenSomethingElse($author, $title, $library_name, $top_post);
});

That's a perfect use case for a Context Manager:

with ( wrap_in_buffer() ) {
     doSomething($to, $library, $thread);
     andThenSomethingElse($author, $title, $library_name, $top_post);
}

There's no callback, so no need to capture anything, and the 
implementation of all the try-catch-finally logic would be baked into 
the language, so the implementation of wrap_in_buffer() would also be 
much simpler.


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #113763 — Nuno Maduro — 2021-03-25T12:31:25+00:00

URL: https://externals.io/message/113740#113763 · In reply to: #113761

Hi,

Thank you for the feedback on this thread so far. Programmers are
opinionated, therefore you will find developers that see themselves using
this RFC and others who don't. Just like "Fibers", "Type-hints", or any
other feature in the language really.

The reason why we believe the vast majority of PHP Developers are going to
appreciate this RFC is because multi-line short closures (aka
Auto-capturing multi-statement closures) *are more simple, shorter to
write, and prettier to read *— and the community love these changes as
proven on "property promotions", "one-line short closures", etc. [1]

Besides, one advantage of this RFC is that it is consistent with the
current syntax of the language and with the short-functions RFC[2]. For
example, by proposing that "fn" keyword indicates a function will
auto-capture variables, by value. And, the "=>" sigil always means
"evaluates to the expression on the right" in all circumstances - one-line
short closures, named functions, arrays, and match() already follow these
patterns. [3]

On the other hand "use (*)" has no usages / or current meaning in the
language.

Thanks,
Nuno.

[1] Pretty much "Brent Roose" have said here:
https://externals.io/email/112010/source
[2] https://wiki.php.net/rfc/short-functions
[3] Check "Auto-capture multi-statement closures" -
https://wiki.php.net/rfc/auto-capture-closure.

---

## #113764 — Mike Schinkel — 2021-03-25T12:44:25+00:00

URL: https://externals.io/message/113740#113764 · In reply to: #113761

> 
> 
> 
> 
> > […]
> 
> That's not quite what I meant. I meant that you can't say "capture by default, but this variable is definitely local".


Yes I can see you want a way to declare a local in an auto-capturing fn(), but respectfully I do not see why using the function() syntax is not a viable alternate solution when and if you want to explicitly not capture a variable.

I said "want" because you will never *need* to as you can always use a variable name that is not in the outer scope. 

And yes I know, someone may come along later and add a named variable in the outer scope that matches your implicit local variable's name and potentially break your code, but again if that is a concern why can't you just use function() instead of fn()?  And wouldn't they actually be breaking their code (the outer code) if they did this?

Respectfully, you seem to be calling out a problem for which there is a tailor-designed solution explicitly recommended in the RFC. How can function() not address your stated concern?


> I'm guessing maybe "$foo = null;" at the top of the function would stop it auto-capturing, but the semantics of what exactly gets captured aren't spelled out in the RFC. That really needs to be added IMO.
> 
> 
> > […]
> 
> Is that a bad thing? In many cases it's probably more efficient, and easier to read.


Depends on what your priorities are.  If you priorities are coding in the absolute most efficient manner and/or with the most clarity, no it is probably not a bad thing.

But if your priorities are coding in the most robust manner where your code is free from side-effects by design — in a functional style —  and the performance difference is insignificant, then yes it is a bad thing. 

And at least one of the pair of RFCs spell out this motivation to allow for more functional style explicitly. 


> > […]
> 
> I didn't mean to say that the "with" statement would replace closures in general, but it would make them unnecessary *for some specific use cases*.


Respectfully again, to argue a use-case could be addressed in a different way than proposed by the RFC when that different way uses a hypothetical language feature that AFAIK does not have an RFC currently under consideration rings hollow to me.

Minimally I would expect you to at least first float the hypothetical on the list to see if there is appetite for it rather than just using is idea to snipe at an RFC that many people appear to support.


> You mentioned:
> 
> > […]


Actually, I did not provide that example. Other people did.  

What I stated was I had other use-cases that concerned me more than transactions, which I already explained in my email. 

However, in no way do I mean to argue against their value for other developers who mentioned them.


> If your current code looks something like this:
> 
> wrap_in_buffer(function($transaction) use ($to, $library, $thread, $author, $title, $library_name, $top_post) {
>     doSomething($to, $library, $thread);
>     andThenSomethingElse($author, $title, $library_name, $top_post);
> });
> 
> That's a perfect use case for a Context Manager:
> 
> with ( wrap_in_buffer() ) {
>     doSomething($to, $library, $thread);
>     andThenSomethingElse($author, $title, $library_name, $top_post);
> }
> 
> There's no callback, so no need to capture anything, and the implementation of all the try-catch-finally logic would be baked into the language, so the implementation of wrap_in_buffer() would also be much simpler.


But thanks for clarifying with examples, because I did ask for that.

That said, "with" is still hypothetical.  Are you planning to champion its inclusion into PHP with a discussion and then follow up RFC?

-Mike

---

## #113765 — olleharstedt@gmail.com — 2021-03-25T13:12:22+00:00

URL: https://externals.io/message/113740#113765 · In reply to: #113763

> prettier to read

Are they though? Because if it implicitly captures anything in scope,
there are more lines to read to figure out what's actually captured.

2021-03-25 13:31 GMT+01:00, Nuno Maduro <enunomaduro@gmail.com>:
> Hi,
>
> Thank you for the feedback on this thread so far. Programmers are
> opinionated, therefore you will find developers that see themselves using
> this RFC and others who don't. Just like "Fibers", "Type-hints", or any
> other feature in the language really.
>
> The reason why we believe the vast majority of PHP Developers are going to
> appreciate this RFC is because multi-line short closures (aka
> Auto-capturing multi-statement closures) *are more simple, shorter to
> write, and prettier to read *— and the community love these changes as
> proven on "property promotions", "one-line short closures", etc. [1]
>
> Besides, one advantage of this RFC is that it is consistent with the
> current syntax of the language and with the short-functions RFC[2]. For
> example, by proposing that "fn" keyword indicates a function will
> auto-capture variables, by value. And, the "=>" sigil always means
> "evaluates to the expression on the right" in all circumstances - one-line
> short closures, named functions, arrays, and match() already follow these
> patterns. [3]
>
> On the other hand "use (*)" has no usages / or current meaning in the
> language.
>
> Thanks,
> Nuno.
>
> [1] Pretty much "Brent Roose" have said here:
> https://externals.io/email/112010/source
> [2] https://wiki.php.net/rfc/short-functions
> [3] Check "Auto-capture multi-statement closures" -
> https://wiki.php.net/rfc/auto-capture-closure.

---

## #113766 — olleharstedt@gmail.com — 2021-03-25T13:12:53+00:00

URL: https://externals.io/message/113740#113766 · In reply to: #113761

I feel like some of these examples would be better covered by command
object pattern and data-transaction objects, instead of FP idioms.
wrap_in_buffer pretty clearly so.

2021-03-25 10:28 GMT+01:00, Rowan Tommins <rowan.collins@gmail.com>:
> 
>
> > […]
>
> That's not quite what I meant. I meant that you can't say "capture by
> default, but this variable is definitely local".
>
> I'm guessing maybe "$foo = null;" at the top of the function would stop
> it auto-capturing, but the semantics of what exactly gets captured
> aren't spelled out in the RFC. That really needs to be added IMO.
>
>
> > […]
>
>
> Is that a bad thing? In many cases it's probably more efficient, and
> easier to read.
>
>
>
>
> > […]
>
>
> I didn't mean to say that the "with" statement would replace closures in
> general, but it would make them unnecessary *for some specific use
> cases*. You mentioned:
>
> > […]
> buffering handlers.
>
> If your current code looks something like this:
>
> wrap_in_buffer(function($transaction) use ($to, $library, $thread,
> $author, $title, $library_name, $top_post) {
>      doSomething($to, $library, $thread);
>      andThenSomethingElse($author, $title, $library_name, $top_post);
> });
>
> That's a perfect use case for a Context Manager:
>
> with ( wrap_in_buffer() ) {
>      doSomething($to, $library, $thread);
>      andThenSomethingElse($author, $title, $library_name, $top_post);
> }
>
> There's no callback, so no need to capture anything, and the
> implementation of all the try-catch-finally logic would be baked into
> the language, so the implementation of wrap_in_buffer() would also be
> much simpler.
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php

---

## #113767 — Mark Randall — 2021-03-25T13:29:02+00:00

URL: https://externals.io/message/113740#113767 · In reply to: #113761

> That's not quite what I meant. I meant that you can't say "capture by 
> default, but this variable is definitely local".

I think if there's one argument against, this would be it, but IMHO it 
is a weakness in PHP as a whole.

The solution would be adding JS-like let / const statements. Which would 
be a benefit to other things too.

---

## #113768 — olleharstedt@gmail.com — 2021-03-25T13:54:05+00:00

URL: https://externals.io/message/113740#113768

2021-03-25 14:29 GMT+01:00, Mark Randall <marandall@php.net>:
> 
> > […]
>
> I think if there's one argument against, this would be it, but IMHO it
> is a weakness in PHP as a whole.
>
> The solution would be adding JS-like let / const statements. Which would
> be a benefit to other things too.

JS does not support "definitely local". No language does, AFAIK.
Unless you count value types.

---

## #113769 — Mark Randall — 2021-03-25T14:10:53+00:00

URL: https://externals.io/message/113740#113769 · In reply to: #113768

> JS does not support "definitely local". No language does, AFAIK.
> Unless you count value types.

We were both refering to block-level variables, which most languages do.

---

## #113770 — Mike Schinkel — 2021-03-25T14:14:26+00:00

URL: https://externals.io/message/113740#113770 · In reply to: #113768

> 
> 
> 2021-03-25 14:29 GMT+01:00, Mark Randall <marandall@php.net>:
> > […]
> 
> JS does not support "definitely local". No language does, AFAIK.
> Unless you count value types.

Actually, at least a few languages on this list have "definitely local" variables:

https://en.wikipedia.org/wiki/List_of_programming_languages

I have had in-depth experience with two of them, the former of which was a dynamic language and both support auto-capturing closures: 

- Clipper 
- GoLang

#fwiw

---

## #113771 — Christian Schneider — 2021-03-25T14:23:14+00:00

URL: https://externals.io/message/113740#113771

Am 25.03.2021 um 14:29 schrieb Mark Randall <marandall@php.net>:
> 
> > […]
> 
> I think if there's one argument against, this would be it, but IMHO it is a weakness in PHP as a whole.

I'm not sure if I misunderstand what you're saying but to me it is one of the greatest things about PHP that everything is local by default (minus a narrow set of well-known and easily enough recognizable things).

> The solution would be adding JS-like let / const statements. Which would be a benefit to other things too.


I disagree that this is the solution. I think JS had to add var and later let because of the unfortunate decision to have C-like scoping rules.
Making scoping in PHP more complex to be able to repeat this mistake in some form seems ill-advised to me.

- Chris

---

## #113772 — olleharstedt@gmail.com — 2021-03-25T14:38:40+00:00

URL: https://externals.io/message/113740#113772 · In reply to: #113771

2021-03-25 15:23 GMT+01:00, Christian Schneider <cschneid@cschneid.com>:
> Am 25.03.2021 um 14:29 schrieb Mark Randall <marandall@php.net>:
> > […]
>
> I'm not sure if I misunderstand what you're saying but to me it is one of
> the greatest things about PHP that everything is local by default (minus a
> narrow set of well-known and easily enough recognizable things).
>
> > […]
>
>
> I disagree that this is the solution. I think JS had to add var and later
> let because of the unfortunate decision to have C-like scoping rules.
> Making scoping in PHP more complex to be able to repeat this mistake in some
> form seems ill-advised to me.
>
> - Chris

You could make the change that *all* variables are now block-scoped,
not function-scoped. That would make auto-capture less dangerous, but
I don't know how much code it would break.

---

## #113773 — Rowan Tommins — 2021-03-25T14:41:12+00:00

URL: https://externals.io/message/113740#113773 · In reply to: #113763

> The reason why we believe the vast majority of PHP Developers are going to
> appreciate this RFC is because multi-line short closures (aka
> Auto-capturing multi-statement closures) *are more simple, shorter to
> write, and prettier to read *— and the community love these changes as
> proven on "property promotions", "one-line short closures", etc.


My main point was that the RFC needs to spell out this argument, rather 
than taking it for granted that everyone agrees on "those situations 
where that is warranted".

Most of the current text should be summarised in a "syntax choices" 
section somewhere near the end. I would like to see much more space 
devoted to:

* Why we need this feature. What has changed since it was left out of 
the arrow functions RFC? What problems is it addressing? Why do you 
think it is the best approach to those problems?
* The exact semantics proposed: How will the variables to be captured be 
determined? Will it distinguish variables which are written before 
they're read, and if so how is that defined? Can auto-capturing closures 
be nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a from 
the outermost scope? And so on...


> Besides, one advantage of this RFC is that it is consistent with the
> current syntax of the language and with the short-functions RFC[2]. For
> example, by proposing that "fn" keyword indicates a function will
> auto-capture variables, by value.


While it's a cute rationalisation, there's no intuitive reason why "fn" 
should have that meaning; we could pick any aspect of the current arrow 
function syntax and say "the 'fn' keyword means that".



> On the other hand "use (*)" has no usages / or current meaning in the
> language.


This is a straw man argument. I could equally say that "fn() { } has no 
usages or current meaning in the language" - of course it doesn't, we 
haven't added it yet!

The "function use() {}" part of "function use(*) {}" has a 
well-established meaning, and "*" to mean "everything" is a notation 
developers are likely to be very familiar with.

The two disadvantages I see with using "fn" as proposed are:

* Because it's shorter, people will decide it's the "better" version, 
when they don't actually need any variable capture. An explicit syntax 
like "use(*)" instead makes this a deliberate choice.
* There is no obvious way to expand it to support any by-reference 
capture, which is something people have previously expressed a desire for.


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #113774 — Mike Schinkel — 2021-03-25T15:02:39+00:00

URL: https://externals.io/message/113740#113774 · In reply to: #113773

> 
> 
> 
> 
> > […]
> 
> 
> My main point was that the RFC needs to spell out this argument, rather than taking it for granted that everyone agrees on "those situations where that is warranted".
> 
> Most of the current text should be summarised in a "syntax choices" section somewhere near the end. I would like to see much more space devoted to:
> 
> * Why we need this feature. What has changed since it was left out of the arrow functions RFC? What problems is it addressing? Why do you think it is the best approach to those problems?
> * The exact semantics proposed: How will the variables to be captured be determined? Will it distinguish variables which are written before they're read, and if so how is that defined? Can auto-capturing closures be nested, i.e. will "fn() { return fn() { echo $a; } }" capture $a from the outermost scope? And so on...
> 
> 
> > […]
> 
> 
> While it's a cute rationalisation, there's no intuitive reason why "fn" should have that meaning; we could pick any aspect of the current arrow function syntax and say "the 'fn' keyword means that".
> 
> 
> 
> > […]
> 
> 
> This is a straw man argument. I could equally say that "fn() { } has no usages or current meaning in the language" - of course it doesn't, we haven't added it yet!
> 
> The "function use() {}" part of "function use(*) {}" has a well-established meaning, and "*" to mean "everything" is a notation developers are likely to be very familiar with.
> 
> The two disadvantages I see with using "fn" as proposed are:
> 
> * Because it's shorter, people will decide it's the "better" version, when they don't actually need any variable capture. An explicit syntax like "use(*)" instead makes this a deliberate choice.

And yet adding " use (*)" makes the syntax longer, which goes against one of the goals many people have for it: to be shorter.

> * There is no obvious way to expand it to support any by-reference capture, which is something people have previously expressed a desire for.

Can you please clarify why "function(...) use(...) {...}" can't be their solution when someone needs by-reference capture?

-Mike

P.S. BTW, if we *had* to enable by-ref for "fn(...)" then I would argue it should be a terse syntax, e.g.:

$callable = fn()(&$foo) => $foo= bar();

---

Next page: https://externals.io/message/113740.md?page=2
