Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement callback methods inside classes (PHP)

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)

like image 938
Gal Avatar asked Apr 06 '10 11:04

Gal


People also ask

How to implement callback/callable variable in PHP?

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.

How to use callback functions with anonymous functions in PHP?

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:

What is a callback in C++?

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.

How to call static methods and functions in PHP?

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.


1 Answers

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);
like image 122
Gordon Avatar answered Sep 30 '22 21:09

Gordon