Return a loop in function php

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

    You should turn it inside out!

    Instead of returning the loop, you could do it this way using Variable functions :

    function myloop($sql, $myFunction){ 
        $query = mysql_query($sql);  
        while(mysql_fetch_assoc($query)) {
            $myFunction($result);
        }
    
    } 
    
    
    function doSomethingWithTheResult($result) {
       echo $result; // just to have something here...
    }
    
    //now the usage:
    myloop("SELECT 1", 'doSomethingWithTheResult');
    

    With a squint, this is similar to the concept of the Template method OOP design pattern.

提交回复
热议问题