开发者

Passing object method to array_map() [duplicate]

This question already has answers here: How to use class methods as callbacks (5 answers) Closed 3 months ago.
    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;
开发者_Python百科

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
)


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));


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);


I tried search for solution but it not works, so I created custom small map function that will do the task for 1 variable passed to the function it simple but will act like map

class StyleService {
  function check_css_block($str){
    $check_end = substr($str,-1) == ';';
    $check_sprator =  preg_match_all("/:/i", $str) == 1;
    $check_sprator1 =  preg_match_all("/;/i", $str) == 1;
    if ( $check_end && $check_sprator && $check_sprator1){
      return $str;
    } else {
      return false;
    }
  }

  function mymap($function_name, $data){
    $result = array();
    $current_methods = get_class_methods($this);
    if (!in_array($function_name, $current_methods)){
      return False;
    }
    for ($i=0; $i<count($data); $i++){
      $function_result = $this->{$function_name}($data[$i]);
      array_push($result, $function_result);
    }
    return $result;
  }


  function get_advanced_style_data($data)

  {
    return $this->mymap('check_css_block', $data);
  }
}

this way you can call a function name as string $this->{'function_name'}() in php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜