Fail-fast on unsupported Header protocol type
[hiphop-php.git] / hphp / doc / extension.yield
blob23b8b81a2affc9023e39ee418629e658b1f47975
2 <h2>yield and generator</h2>
4 HipHop extends PHP to include Python and C#-style generators. If you're
5 unfamiliar with the concept, see
6 [[http://docs.python.org/tutorial/classes.html#generators | the Python docs]].
7 As in Python, the <i>yield</i> keyword marks the enclosing function as a
8 generator:
10   function foo() {
11     $a = 123;
12     yield $a;
13     $a = 456;
14     yield $a;
15   }
17   foreach (foo() as $a) {
18     print "$a,";
19   }
21 The above program outputs "123,456,". To abort a generator sequence, use "yield
22 break".
24   function bar() {
25     $a = 123;
26     // this will stop the "foreach" immediately without any value returned
27     if ($abort) yield break;
28     yield $a;
29     $a = 456;
30     yield $a;
31   }
33 Generators must observe the following restrictions:
35 - Generators are <b>not recursive</b>. In the above example, foo() cannot call
36   foo() while iterating.
37 - Generators are <b>called once</b>: foo() cannot be called again after it's
38   done iterating.
39 - Do not call the rewind() method of the objects (of class Iterator) returned by
40   iterator functions.
42 Also, yield in HipHop also supports passing a value from outside of the
43 generator.
45   function foo() {
46     $a = yield 5;
47     yield $a + 1;
48   }
50 From outside the generator, instead of resuming the generator with
51 Generator::next(), one can call Generator::send() to pass a value, which
52 will be assigned to $a, back into the generator.
54 Note that the yield expression in the above example is not really an expression;
55 it can only appear on its own on the RHS of an assignment statement. This is to
56 avoid the complicated evaluation order problem in bizarre expressions like
57 "($a = yield 5) * (yield $a + 3) - ($a = yield 4)".