views:

160

answers:

3

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)

+3  A: 

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);
Gordon
Thanks, I got the two confused.
sombe
A: 

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);
KennyTM
A: 

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.

symcbean
No offense, but this is overcomplicated and using static in functions is bad style
Gordon