<?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;//Line output large file}/*------------------------------------------- ----------------------------*/function xrange ($start, $end, $step = 1) {for ($i = $start; $i <= $end; $i + = $step ) {yield $i; }} foreach (Xrange (1, +) as $num) {echo $num, "\ n"; Generate Large Array}/*-----------------------------------------------------------------------*/function get () {$sql = "SELECT * From ' user ' limit 0,500000000; $stat = $pdo->query ($sql); while ($row = $stat->fetch ()) {yield $row;//row-by-line readout of database row}}foreach (get () as $row) {var_dump ($row);}/*----- ------------------------------------------------------------------------*/function Middleware ($handlers, $ arguments = []) {//function stack $stack = []; $result = null; Foreach($handlers as $handler) {//reset before each loop, only the return value of the last handler is saved $result = null; $generator = Call_user_func_array ($handler, $arguments); if ($generator instanceof \generator) {//The co-function is put into the stack, ready for re-entry $stack [] = $generator; Gets the parameter $yieldValue = $generator->current () of the process return; Check whether to re-enter the function stack if ($yieldValue = = = False) {break; }} elseif ($generator!== null) {//re-enter the parameters $result = $generator; }} $return = ($result!== null); The process function is out of the stack 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 Generator Yield Use example