PHP callback function not working on object functions

I have an array and I want to apply MySQLi->real_escape_string for each element of the array through array_walk , but this does not work:

 array_walk($array, '$mysqli->real_escape_string'); 

He gives this error:

Warning: array_walk () expects parameter 2 to be a valid callback, the function '$ mysqli-> real_escape_string' was not found, or the function name is incorrect in C: \ wamp \ www \ ts.php on line 69

$mysqli is a valid object and works fine if I do $mysqli->real_escape_string('anything') anything else.

My question is: Can't pass functions to an object as a callback? Or am I doing something wrong.


IMPORTANT: I know that I can create my own callback function and implement $ mysqli-> real_escape_string in it. But I want to know if a callback cannot be used as a function of an object?

+4
source share
3 answers

As you can read on the php callback page, you should use:

 # produces an error array_walk($array, array($msqli, 'real_escape_string')); array_map($array, array($msqli, 'real_escape_string')); 
+8
source

If you call a method inside an object that you must pass into an array, the first element is an object / context, and then the second should be a method:

A small example

 function callback() { //blah } 

the above is called a function and should be called like this: array_walk($array, 'callback');

 class object() { public function callback() { } } 

the above callback is called a method, it is almost the same as a function, but since it has a parent context inside the class, so it should be called like this:

 $object = new object(); array_walk($array, array($object , 'callback')); 

MySQLi is an object-oriented library, so after initializing the mysqli object, you must call the "method" as follows:

 array_walk($array, array($msqli, 'real_escape_string')); 

Also, as mentioned above, array_walk will move both the key and value into the mysql object, which will result in accurate escaping, you should use array_map to move only the values:

array_map($array, array($msqli, 'real_escape_string'));

+9
source

array_walk only allows passing a user-defined function as a callback, not a PHP function or method. To do this, I will try the following:

 foreach($array as &$value) { $value = $mysqli->real_escape_string($value); } 

Passing a value by reference allows you to change it in a foreach loop, as a result of which each member of the array is escaped.

0
source

All Articles