How to implement callback methods inside classes (PHP)

I need to use the class callback method for 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? (I mean, by the second parameter passed to array_map )

+6
arrays methods php callback class
source share
4 answers

I don't think you want array_filter , but array_map

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

but again, you can also do

 return array_map('mysql_real_escape_string', $array); 
+9
source share

array_filter removes elements that do not satisfy the predicate. Do you mean array_map ?

 return array_map(array($this, "escape_string_for_db"), $array); 
0
source share

That should work. You can check the same weather function as your parameter - a string or an 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; } 
0
source share

The simplest solution would be to pass the method as a 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"); } } 

FROM.

-one
source share

All Articles