Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

php - Can a method be used as an array_map function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...