11

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)

tom91136
  • 8,662
  • 12
  • 58
  • 74
  • "I have no choice but to rewrite some part of my code to make it 5.2 compatible." Or get a new host that isn't insecure by default. – ceejayoz Aug 29 '12 at 13:53
  • Tell your host that you want PHP upgraded, sometimes they will actually do it. – Wesley Murch Aug 29 '12 at 13:54
  • they actually refused saying that : '5.2 supports other client better since it has "less strict standards" than 5.3' – tom91136 Aug 29 '12 at 13:56

4 Answers4

19

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.

nickb
  • 59,313
  • 13
  • 108
  • 143
4

Try using :

print_r(array_map(array($this, "mapKeyValue") , $arr, $arr2));

You need to call the function using $this.

Cosmin
  • 1,482
  • 12
  • 26
  • 3
    `&$this` will not boost performance, and in later versions of PHP call-time pass-by-reference has been removed. – nickb Aug 29 '12 at 14:05
0
array_map(array($this, 'mapKeyValue'), $arr, $arr2);
TheHe
  • 2,933
  • 18
  • 22
0

Make sure your that callback method is public.

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

print_r(array_map(array($this, "mapKeyValue") , $arr, $arr2));
Patrick Thach
  • 138
  • 1
  • 1
  • 6