1. 程式人生 > >PHP生成器yield使用示例

PHP生成器yield使用示例

一個 get() while 函數 sel 循環 all pre var

<?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]);

  

PHP生成器yield使用示例