PHP基礎之生成器3——生成器對象
當一個生成器函數被第一次調用,會返回一個內部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!
相關文章:
