Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php callback function in class

for some reasons, our hosting company used PHP 5.2 and doesn't even have mysqli and PDO pre-installed.

I have no choice but to rewrite some part of my code to make it 5.2 compatible.

so, here is my question:

In PHP 5.2 Anonymous function is not supported, so i did the following test to make sure I'm changing the code correctly:

class foo{

    public function toString(){
        $arr = array("a", "b");
        $arr2 = array("c", "d");
        print_r(array_map('mapKeyValue', $arr, $arr2));
    }

    private function mapKeyValue($v, $k){
        return $k."='".$v."'";
    }
}

$foo = new foo();
echo $foo->toString();

but the above would give me :

Warning: array_map() expects parameter 1 to be a valid callback, function 'mapKeyValue' not found or invalid function name in ....
PHP Warning: array_map() expects parameter 1 to be a valid callback, function 'mapKeyValue' not found or invalid function name in ....

what is the correct way to do :

array_map('mapKeyValue', $arr, $arr2);

within a class?

PS: Is it a good enough reason to change hosting company because they use PHP 5.2?(i got a contract with about 7 month left)

like image 524
tom91136 Avatar asked Aug 29 '12 13:08

tom91136


People also ask

What is the callback function in PHP?

A callback function (often referred to as just "callback") is a function which is passed as an argument into another function.

Are PHP functions callable?

The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.

When callback is executed?

A callback function is a function that occurs after some event has occurred. The reference in memory to the callback function is usually passed to another function. This allows the other function to execute the callback when it has completed its duties by using the language-specific syntax for executing a function.

What is callback function explain with an example?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.


1 Answers

Use $this and an array as the callback:

array_map( array( $this, 'mapKeyValue'), $arr, $arr2);

And, just to be sure, this is tested with PHP 5.2.17 and is confirmed working.

like image 84
nickb Avatar answered Sep 28 '22 04:09

nickb