Re: [RFC] Context Managers, v2
| From: | Larry Garfield | Date: | Thu, 12 Nov 2026 15:15:07 +0000 |
| Subject: | Re: [RFC] Context Managers, v2 | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-133089@lists.php.net to get a copy of this message | ||
On Wed, Nov 11, 2026, at 8:46 AM, Larry Garfield wrote:
>> «A return statement inside the BODY will return from the function the
>> code is currently executing in. A finally block in the generator
>> context manager will still be executed, but otherwise control returns
>> to the function's caller.»
>> This is also hard to get for me.
>> Can you detail what this would output:
>> function context(): \Generator {
>> echo "A\n";
>> yield "B";
>> echo "C\n";
>> return "D";
>> }
>> var_dump(
>> using (context() => $c) {
>> echo "E\n";
>> return "F";
>> }
>> );
>
> I believe (without actually running it) that would output:
>
> A
> E
>
> The return "F" terminates the function that the var_dump()/using()
> construct is in. The generator is discarded without ever reaching its
> end, so the generator's return statement is never reached.
>
> That said, you have brought up an interesting question, I have no idea
> what happens when you var_dump() a compound expression like this that
> returns. Something for Arnaud to write tests for. 0:-)
>
> --Larry Garfield
Actually I'm wrong. I checked with Arnaud, and it will print A E C.
When you return from the CM block, the generator is first resumed so that it gets a chance to do its
cleanup, in this case printing C. When it completes, then the function return happens. The
var_dump() is never called, because the function returned before that happened.
I have reworded the RFC a bit to make that clearer. Thanks for calling it out.
--Larry Garfield