標籤:資料庫 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使用樣本