tags:

views:

246

answers:

1

I want to do something like this:

class Cls {
  function fun($php) {
    return 'The rain in Spain.';
  }
}

$ar = array(1,2,3);
$instance = new Cls();
print_r(array_map('$instance->fun', $ar));
               // ^ this won't work

but the first argument to array_map is supposed to be the name of the function. I want to avoid writing a wrapper function around $instance->fun, but it doesn't seem like that's possible. Is that true?

+16  A: 

Yes, you can have callbacks to methods, like this:

array_map(array($instance, 'fun'), $ar)

see the callback type in PHP's manual for more info

Jani Hartikainen
Neat. Didn't know this was doable. +1
Paolo Bergantino
If the method is static array('Class', 'StaticMethod') works too
Philippe Gerber
Thanks Jani. This is way cool!
allyourcode
This is sooo useful (And not documented on php.net's array_map page. Thanks :)
Candidasa