开发者

How to implement callback methods inside classes (PHP)

开发者 https://www.devze.com 2022-12-25 14:48 出处:网络
I need to use a class callback method on an array inside another method (the callback function belongs to the class).

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

c开发者_如何学JAVAlass 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)


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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号