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 = $generator->current();

            //检查是否重入函数栈
            if ($yieldValue === false) {
                break;
            }
        } elseif ($generator !== null) {
            //重入协程参数
            $result = $generator;
        }
    }

    $return = ($result !== null);
    //将协程函数出栈
    while ($generator = array_pop($stack)) {
        if ($return) {
            $generator->send($result);
        } else {
            $generator->next();
        }
    }
}
$abc = function(){
    echo "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]);

  

转载于:https://www.cnblogs.com/isuben/p/7061448.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值