Hey Larry, > Am 19.01.2026 um 16:58 schrieb Larry Garfield <[email protected]>: > > As noted in Future Scope, we can add function-based context managers as well > based on generators. At the moment we're not convinced it's necessary, but > it's a straightforward add-on if we find that always writing a class for a > context manager is too cumbersome. > > The issue with punting this behavior to user-space is that a library cannot > provide this sort of functionality in a clean way. > > In an ideal world, if we had auto-capturing long-closures, then I would agree > this is largely unnecessary and could instead be implemented like so (to > reuse the examples from the RFC): > > $conn->inTransaction(function () { > // SQL stuff. > }); > > $locker->lock('file.txt', function () { > // File stuff. > }); > > $scope->inScope(function () { > $scope->spawn(yadda yadda); > }); > > $errorHandlerScope->run(fn() => null, function () { > // Do stuff here with no error handling. > }); > > And so forth. If we had auto-capturing closures, I would probably argue that > is a better approach. > > However, auto-capturing closures have been rejected several times, and I have > no confidence that we will ever get them. (Whether you approve or disapprove > of that is your personal opinion.) The current alternative involves using > lots of `use` clauses, which is needlessly clunky to the point that folks try > to avoid it. > > I literally have code like this in a project right now, and I've had to do > this many times: > > public function parseFolder(PhysicalPath $physicalPath, LogicalPath > $logicalPath, array $mounts): bool > { > return $this->cache->inTransaction(function() use ($physicalPath, > $logicalPath, $mounts) { > // Lots of SQL updates here. > }); > } > > That's just gross. :-) This is exactly the example that's been used in the > past to argue in favor of auto-capturing closures, but it's never been > successful.
I fully agree that this is gross. I have just created a comprehensive RFC https://wiki.php.net/rfc/scope-functions to address this underlying problem you describe. It does address quite a few of the main issues people had with trivial auto-capturing Closures which would simply clone the symbol table. I personally really don't like this Context Managers RFC given the apparent complexity it has (only for heavyweight usages basically, library style - you wouldn't just create ContextManager implementing classes ad hoc for everything). Thus, I'd like to ask you to consider my RFC first and give feedback on it, and possibly - obviously only if you think my RFC is a good choice for the language - pause this RFC for as long as mine is under discussion. Thanks, Bob
