Re: Re: Generators in PHP

From: Date: Thu, 09 Aug 2012 02:49:59 +0000
Subject: Re: Re: Generators in PHP
References: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  Groups: php.internals 
Request: Send a blank email to internals+get-62092@lists.php.net to get a copy of this message
> > One question, though: It looks based on the voting like finally {} blocks > are going in. So... what should happen in the following situation: > > function stuff() { > try { > foreach (range(1, 100) as $i) { > yield $i; > } > } > finally { > print "All done"; > } > } > > Does "All done" get printed once, or 101 times? Similarly: > > function things() { > $i = 1; > try { > while (true) { > yield $i++; > } > } > finally { > print "All done"; > } > } > > That will run indefinitely. So will "All done" ever print, or does that > finally become unreachable? > > (I have no clue what the behavior "should" be in these cases, just that it > should be sorted out sooner rather than later.) > Based on my understanding of both RFCs, I don't see that this would be a conflict or lead to unexpected behavior. As stated by the generators RFC: "When you first call the generator function ($lines = getLinesFromFile($fileName)) the passed argument is bound, but nothing of the code is actually executed. Instead the function directly returns a Generator object.". So in the event we are calling the function stuff(), nothing should actually be executed, and as we iterate over the traversable object the generator should be "passing control back and forth between the generator and the calling code". This would be indicated by the "yield" keyword present in the function. Meaning you should see the expected result and finally should only ever be called once in your first example. As for you second example... Obviously if you've created an infinite loop you've made everything outside of the loop unreachable, whether you're using generators or not. However, I'll let the author of the RFC provide any clarification or corrections where I might be wrong.

« previous php.internals (#62092) next »