首页 > 代码库 > PHP生成器yield使用示例
PHP生成器yield使用示例
<?php function getLines($file) { $f = fopen($file, ‘r‘); try { while ($line = fgets($f)) { yield $line; } } finally { fclose($f); } } foreach (getLines("sql.txt") as $n => $line) { echo $line; //逐行输出大文件 } /*-----------------------------------------------------------------------*/ function xrange($start, $end, $step = 1) { for ($i = $start; $i <= $end; $i += $step) { yield $i; } } foreach (xrange(1, 1000) as $num) { echo $num, "\n"; //生成大数组 } /*-----------------------------------------------------------------------*/ function get(){ $sql = "select * from `user` limit 0,500000000"; $stat = $pdo->query($sql); while ($row = $stat->fetch()) { yield $row;//逐行读出数据库行 } } foreach (get() as $row) { var_dump($row); } /*-----------------------------------------------------------------------------*/ function middleware($handlers,$arguments = []){ //函数栈 $stack = []; $result = null; foreach ($handlers as $handler) { // 每次循环之前重置,只能保存最后一个处理程序的返回值 $result = null; $generator = call_user_func_array($handler, $arguments); if ($generator instanceof \Generator) { //将协程函数入栈,为重入做准备 $stack[] = $generator; //获取协程返回参数 $yieldValue = http://www.mamicode.com/$generator->current();"this is abc start \n"; yield; echo "this is abc end \n"; }; $qwe = function (){ echo "this is qwe start \n"; $a = yield; echo $a."\n"; echo "this is qwe end \n"; }; $one = function (){ return 1; }; middleware([$abc,$qwe,$one]);
PHP生成器yield使用示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。