Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing object method to array_map()

Tags:

arrays

php

    class theClass{          function doSomeWork($var){             return ($var + 2);          }           public $func = "doSomeWork";           function theFunc($min, $max){             return (array_map(WHAT_TO_WRITE_HERE, range($min, $max)));          }     }  $theClass = new theClass; print_r(call_user_func_array(array($theClass, "theFunc"), array(1, 5))); exit; 

Can any one tell what i can write at WHAT_TO_WRITE_HERE, so that doSomeWork function get pass as first parameter to array_map. and code work properly.

And give out put as

Array (     [0] => 3     [1] => 4     [2] => 5     [3] => 6     [4] => 7 ) 
like image 660
Poonam Bhatt Avatar asked Dec 28 '10 14:12

Poonam Bhatt


2 Answers

To use object methods with array_map(), pass an array containing the object and the objects method name. For same-object scope, use $this as normal. Since your method name is defined in your public $func property, you can pass func.

As a side note, the parentheses outside array_map() aren't necessary.

return array_map( [$this, 'func'], range($min, $max)); 
like image 60
BoltClock Avatar answered Sep 25 '22 17:09

BoltClock


The following code provides an array of emails from an $users array which contains instances of a class with a getEmail method:

    if(count($users) < 1) {         return $users; // empty array     }     return array_map(array($users[0], "getEmail"), $users); 
like image 24
psychoslave Avatar answered Sep 22 '22 17:09

psychoslave