将对象方法传递给 array_map() [英] Passing object method to array_map()
问题描述
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;
谁能告诉我可以在 WHAT_TO_WRITE_HERE 写什么,以便 doSomeWork 函数作为第一个参数传递给 array_map.和代码正常工作.
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.
并给出放置
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
)
推荐答案
要在 array_map()
中使用对象方法,请传递一个包含对象实例和方法名称的数组.对于相同对象范围,照常使用 $this
.由于您的方法名称是在您的 public $func
属性中定义的,您可以传递 $this->func
.这适用于大多数接受 回调的函数a> 作为参数.
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.
作为旁注,array_map()
外的括号不是必需的.
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屋!