Return a loop in function php

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

    No, you can't. You can pass a function to a function, though:

    // The myloop function, with another name.
    function query($sql, $rowcallback)
    {
      $query = mysqli_query($sql); // use mysqli, not mysql
      while 
        ( ($row = mysql_fetch_assoc($query)) &&
          call_user_func($rowcallback, $row) );
    }
    
    // The code to process a row.
    function processRow(array $row)
    {
       // Use your row here..
       var_dump($row);
    
       return true; // You can return false to break processing.
    }
    
    //calling:
    query($yourSelf, 'processRow');
    

    Instead of passing the function by name, you can also use anonymous functions, depending on your php version:

    //calling:
    query($yourSelf, 
      function(array $row)
      { 
        var_dump($row); 
        return true; // You can return false to break processing.
      });
    

    The function which is called from the callee is often called a callback. call_user_func is the best way to call a callback, since it will also accept methods and static methods, not just functions, so you're more flexible.

提交回复
热议问题