Passing object method to array_map()

前端 未结 2 1252
天命终不由人
天命终不由人 2020-12-29 21:21
    class theClass{
         function doSomeWork($var){
            return ($var + 2);
         }

         public $func = \"doSomeWork\";

         function theFunc         


        
相关标签:
2条回答
  • 2020-12-29 22:09

    To use object methods with array_map(), pass an array containing the object instance and the method name. For same-object scope, use $this as normal. Since your method name is defined in your public $func property, you can pass $this->func. This applies to most functions that accept a callback as an argument.

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

    return array_map(array($this, $this->func), range($min, $max));
    
    0 讨论(0)
  • 2020-12-29 22:10

    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);
    
    0 讨论(0)
提交回复
热议问题