Re: [RFC] Short Closures 2, aka auto-capture take 3
| From: | Rowan Tommins | Date: | Thu, 30 Jun 2022 08:19:05 +0000 |
| Subject: | Re: [RFC] Short Closures 2, aka auto-capture take 3 | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-118126@lists.php.net to get a copy of this message | ||
On 29/06/2022 23:31, Dan Ackroyd wrote:
Imagine some code that looks like this:
// Acquire some resource e.g. an exclusive lock.
$some_resource = acquire_some_resource();
$fn = fn () {
// Free that resource
$some_resource = null;
}
// do some stuff that assumes the exclusive
// lock is still active.
// call the callback that we 'know' frees the resource
$fn();
That's a not unreasonable piece of code to write
For that to work, it would require the variable to be captured by reference, not value. Writing to a variable captured by value, like writing to a parameter passed by value, is just writing to a local variable.
In fact, the "optimisation" is in my opinion a critical part of the semantics, to avoid the opposite problem:
// Acquire some resource e.g. an exclusive lock.
$some_resource = acquire_some_resource();
$fn = fn () {
// Use a variable that happens to have the same name // A naive implementation would see $some_resource mentioned, and capture it // Over-writing the local variable here makes no difference; the closure still holds the value for next time $some_resource = 'hello';} // Free what we believe is the last pointer, to trigger the destructor unset($some_resource); // If $some_resource gets captured, it can only be released by destroying the closure unset($fn); Regards, -- Rowan Tommins [IMSoP]