Re: [RFC] Context Managers

From: Date: Fri, 28 Nov 2025 09:00:52 +0000
Subject: Re: [RFC] Context Managers
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-129468@lists.php.net to get a copy of this message
Hi

Am 2025-11-06 13:18, schrieb Rowan Tommins [IMSoP]:
I think the relationship to Iterators is significant: if you put an iterator in a variable, it's perfectly possible to use it in two different foreach statements, or manually call the interface methods, and get very confusing results. But most of the time, you don't take a reference to the iterator at all, and the same would be true of Context Managers: foreach ( $foo->iterate() as $item ) { ... } with ( $foo->guard() as $resource ) { ... }
The reference to the sibling thread probably fits even better here than in my previous reply. So I'm putting another reference: https://news-web.php.net/php.internals/129467
there's nothing stopping you calling __construct or __destruct as normal methods, and causing all sorts of unintended behaviour.
That is *technically* true and there are indeed some “expert-level” use cases where calling these manually - except for parent:: I guess - is required (e.g. lazy objects), but there's a very significant difference: Those are magic methods following the naming scheme of magic methods. The __ prefix is a visual indicator that the methods are somehow special and probably not meant to be used directly. The documentation at https://www.php.net/manual/en/language.oop5.magic.php states (highlighting mine):
Magic methods are special methods which **override PHP's default's action** when certain actions are performed on an object. All methods names **starting with __** are reserved by PHP.
This is not true for the context manager methods. From a developer's PoV these are normal methods on a class with nothing screaming “be careful”. The interface *could* serve as a invitation for folks to read the documentation on how the interface methods are meant to be used, but we all know how that works in practice with an IDE suggesting normal-looking methods that appear to do the right thing (until they don't). Best regards Tim Düsterhus

Thread (33 messages)

« previous php.internals (#129468) next »