PHP基礎之生成器3——生成器對象
當一個生成器函數(shù)被第一次調用,會返回一個內部Generator類的對象. 這個對象以和前臺迭代器對象幾乎同樣的方式實現(xiàn)了Iterator?接口。
Generator?類中的大部分方法和Iterator?接口中的方法有著同樣的語義, 但是生成器對象還有一個額外的方法:?send().
CautionGenerator?對象不能通過new實例化
Example #1 The?Generator?class
<?php class Generator implements Iterator {public function rewind(); //Rewinds the iterator. 如果迭代已經(jīng)開始,會拋出一個異常。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); // 發(fā)送給定值到生成器,作為yield表達式的結果并繼續(xù)執(zhí)行生成器. }?>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!
相關文章:
1. 基于Surprise協(xié)同過濾實現(xiàn)短視頻推薦方法示例2. vue-electron中修改表格內容并修改樣式3. PHP獲取時間戳等相關函數(shù)匯總4. AJAX實現(xiàn)文件上傳功能報錯Current request is not a multipart request詳解5. 不使用XMLHttpRequest對象實現(xiàn)Ajax效果的方法小結6. 推薦一個好看Table表格的css樣式代碼詳解7. ASP新手必備的基礎知識8. ASP常用日期格式化函數(shù) FormatDate()9. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式10. 微信小程序實現(xiàn)商品分類頁過程結束
