Re: [RFC] Auto-capture multi-line closures and shortfunctions take 2
| From: | Andreas Leathley | Date: | Sun, 28 Mar 2021 11:29:41 +0000 |
| Subject: | Re: [RFC] Auto-capture multi-line closures and shortfunctions take 2 | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-113825@lists.php.net to get a copy of this message | ||
On 27.03.21 17:05, Rowan Tommins wrote:
My biggest concern with automatic capture is the potential for *accidentally* capturing variables - that is, intending to introduce a local variable inside the closure, but capturing a variable from the outer scope that happens to have the same name. This is less of an issue with capture by value, but can still mean resources not being freed, e.g. a large array of data not being freed from memory, or an object destructor not executing when expected. This is more likely in PHP than many other languages, because there is no requirement, or even an option, to explicitly declare a local variable in the closure. It's not a new problem, but since single-expression closures are unlikely to use many local variables, it's probably not one that's been given lots of thought.I do think it is great that you are thinking about how this can negatively effect memory or performance (and things like destructors) and if things can be improved. But do the same problems not exist when binding the current class to an anonymous function - whenever an anonymous function is declared in a class (no matter if by function or fn) the whole class is bound to that function, if you don't explicitely use "static function". That binding can encompass many variables and other classes etc., which is common nowadays with dependency injection, yet I have not heard much about problems surrounding this. Binding the variables from the current scope seems like a smaller impact compared to already binding the whole class and all its dependencies. I would welcome any way of automatically capturing all local variables, as this would be a big "quality-of-life" improvement similar to constructor property promotion, to avoid a lot of boilerplate code. I would not use it that much, but when I use it, it would be a big improvement. Using "fn" for this seems consistent to me, and I don't think people would always use it just because it is shorter - and IDEs and static analyzers could detect and discourage use of "fn" if "function" would be sufficient.