Return a loop in function php

后端 未结 7 1216
忘了有多久
忘了有多久 2021-01-13 14:04

Is it possible to return a loop? not the result but the loop it self. I want to create a function in php. For example like this.

function myloop($sql){
$quer         


        
7条回答
  •  野的像风
    2021-01-13 14:50

    In PHP 5.5+ it is possible, using the yield keyword instead of return (this is called a generator):

    function myloop($sql) {
        $query = mysql_query($sql);
        while (($row = mysql_fetch_assoc($query))) {
            yield $row;
        }
    }
    
    foreach (myloop('SELECT * FROM foo') as $row) {
        // do something with $row
    }
    

    This is not much different from what you could do with iterators in older PHP, but the code is much cleaner.

提交回复
热议问题