传递对象法array_map() [英] Passing object method to array_map()

查看:222
本文介绍了传递对象法array_map()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类theClass描述{
         功能doSomeWork($ VAR){
            回报($ VAR + 2);
         }         公共$ FUNC =doSomeWork;         功能theFunc($ min时,最大$){
            返回(array_map(WHAT_TO_WRITE_HERE,范围($分钟,$最大值)));
         }
    }$ theClass描述=新theClass描述;
的print_r(call_user_func_array(阵列($ theClass描述,theFunc),阵列(1,5)));
出口;

任何一个可以告诉我可以在WHAT_TO_WRITE_HERE写,让doSomeWork功能得到传递,以array_map第一个参数。和code正常工作。

并给出了把为

 阵列

    [0] => 3
    [1] => 4
    [2] =>五
    [3] => 6
    [4] => 7


解决方案

要使用与对象的方法array_map(),传递包含对象实例和方法名称的数组。对于相同的对象范围,使用 $这种正常。由于您的方法名在定义公共$ FUNC 属性,可以通过 $这个 - > FUNC 。这适用于接受回调作为参数大部分功能

作为一个方面说明,外 array_map括号()是没有必要的。

 返回array_map(阵列($此,这 -  $> FUNC),范围($ min时,最大$));

    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
)

解决方案

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

这篇关于传递对象法array_map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆