PHP產生器yield使用樣本

來源:互聯網
上載者:User

標籤:資料庫   result   yield   open   傳回值   and   mit   break   --   

<?phpfunction 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使用樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.