Tutorial :How to implement callback methods inside classes (PHP)



Question:

I need to use a class callback method on an array inside another method (the callback function belongs to the class).

class Database {          public function escape_string_for_db($string){               return mysql_real_escape_string($string);        }          public function escape_all_array($array){               return array_map($array,"$this->escape_string_for_db");        }  }  

Is this the right way to go about that? (I mean, in terms of the second parameter passed to array_map)


Solution:1

I don't think you want to array_filter, but array_map

return array_map(array($this, 'escape_string_for_db'), $array);  

but then again, you can just as well do

return array_map('mysql_real_escape_string', $array);  


Solution:2

array_filter deletes elements which does not satisfy the predicate. Do you mean array_map?

return array_map(array($this, "escape_string_for_db"), $array);  


Solution:3

This should work. You can check in the same function weather your parameter is string or array.

class Database {      public function escape_string_for_db($data)    {      if( !is_array( $data ) )      {        $data =mysql_real_escape_string($data);         }      else      {        //Self call function         $data = array_map(array( 'Database ', 'escape_string_for_db' ), $data );      }    return $data;    }  


Solution:4

Simplest solution would be to to pass the method as the callback - see http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback

Alternatively, write a wrapper function:

function wrap_callback($target, $use_obj=false)  {    static $obj;    if ($use_obj) {       if (method_exists($target, 'callback')) {          $obj=$target;          return true;       } else {          trigger_error("callback declared for something with no callback method");          return false;       }    }    return $obj->callback($target);  }  

Then:

class Database {      public callback($string){           return mysql_real_escape_string($string);    }      public function escape_all_array($array){           wrap_callback($this, true); // register callback           return array_filter($array,"wrap_calback");    }  }  

C.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »