Return a loop in function php

后端 未结 7 1286
忘了有多久
忘了有多久 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:42

    No, but you can simulate that with an Iterator for stable released PHP as of today. In PHP 5.5 there will be generators that is close, too.

    $lazyQuery = new SqlResultItertor($sql);
    foreach ($lazyQuery as $assoc) {
        $assoc; # the result, one per row
    }
    

    BTW: PDO and MySqli offer this already out of the box (not lazy query, but the result is traversable), for mysql you need to write such an iterator-result object your own.

    For some mysql_* functions related code, see this answer. However the general suggestion as of today is to use PDO or mysqli instead, those offer more out of the box. See How to successfully rewrite old mysql-php code with deprecated mysql_* functions?

提交回复
热议问题