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
)
A callback/callable variable can act as a function, object method and a static class method. There are various ways to implement a callback. Some of them are discussed below: Standard callback: In PHP, functions can be called using call_user_func () function where arguments is the string name of the function to be called.
Use an anonymous function as a callback for PHP's array_map () function: User-defined functions and methods can also take callback functions as arguments. To use callback functions inside a user-defined function or method, call it by adding parentheses to the variable and pass arguments as with normal functions:
A callback is considered a function reference/object with the type callable. It can act as an object method, a function, or a static class method. Here, we will demonstrate the ways of using standard callbacks, static class method callbacks, object method callbacks, as well as closure callbacks.
In PHP, you can call functions with the help of the call_user_func () function. The argument is the string name of the function that is going to be called. In PHP, you can call static methods with the help of call_user_func (). Here, the argument is an array that includes the class string name and the method within it to be called.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With