Created
March 23, 2022 09:26
-
-
Save IMSoP/da46cbd7d9e635cee353ec80f84d512d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here are three things I'd like to see in any new auto-capturing closures RFC: | |
1. JUSTIFICATION | |
Don't assume that everyone already thinks it's necessary and desirable. | |
Try to come up with some real-life examples where you would want to use it. | |
Acknowledge the possible down-sides, and explain why you think they're | |
justified. | |
Be aware that the current set of features is not an accident, it's what was | |
agreed on in previous discussions. In particular, see this summary of the | |
series of RFCs that led up to the "fn() => expression" feature: | |
https://externals.io/message/113740#113833 | |
2. SYNTAX | |
I am not at all convinced that "auto-capture" and "short" should go | |
together. We could make "fn" a synonym for "function" independent of | |
auto-capturing, so let's consider the syntax more carefully. | |
Do we want auto-capture to be considered the default, or an opt-in | |
for certain use cases, and how can the syntax reflect that? | |
Do we want to allow a mixture of auto-capture and by-reference capture, | |
and what would that look like? | |
My preference remains for "use(*)" as a visible opt in to auto-capture, | |
with "use(*, &$foo)" to mean "$foo by reference, everything else needed | |
by value". | |
3. SEMANTICS | |
Unlike most languages, PHP lacks any keyword or syntax to declare a | |
local variable, because variables are local by default. That means | |
we need to define exactly which variables mentioned in a closure | |
should be captured, and which should be local to the closure. | |
Even though capture is by value, capturing a variable unexpectedly | |
has an impact on object and resource lifetime (e.g. closing a network | |
connection in a destructor), and could leak memory for large values | |
(e.g. arrays and strings). | |
(This is technically true of the existing short closures, but it's | |
very rare to want a purely local variable inside a single expression.) | |
One option would be to introduce a var/let keyword for block scoping | |
first (as a separate RFC) and then auto-capture could mean "capture | |
everything that's not block scoped". | |
-- | |
Rowan Tommins | |
[IMSoP] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment