當一個產生器函數被第一次調用,會返回一個內部Generator類的對象. 這個對象以和前台迭代器對象幾乎同樣的方式實現了Iterator 介面。
Generator 類中的大部分方法和Iterator 介面中的方法有著同樣的語義, 但是產生器對象還有一個額外的方法: send().
CautionGenerator 對象不能通過new執行個體化
Example #1 The Generator class
<?php class Generator implements Iterator { public function rewind(); //Rewinds the iterator. 如果迭代已經開始,會拋出一個異常。 public function valid(); // 如果迭代關閉返回false,否則返回true. public function current(); // Returns the yielded value. public function key(); // Returns the yielded key. public function next(); // Resumes execution of the generator. public function send($value); // 發送給定值到產生器,作為yield運算式的結果並繼續執行產生器. }?>
Generator::send()
當進行迭代的時候Generator::send() 允許值注入到產生器方法中. 注入的值會從yield語句中返回,然後在任何使用產生器方法的變數中使用.
Example #2 Using Generator::send() to inject values
<?php function printer() { while (true) { $string = yield; echo $string; } } $printer = printer(); $printer->send('Hello world!');?>
以上常式會輸出:
Hello world!