6

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)

4 Answers 4

9

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I got the two confused.
0

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);

Comments

0

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;
  }

Comments

-1

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.