No, you canโt. You can pass a function to a function, but:
// 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 a 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. });
A function that is called from the called party is often called a callback. call_user_func is the best way to call a callback, as it will also accept methods and static methods, not just functions, so you are more flexible.
source share