如何使用类方法作为回调函数?
问题描述:
如果我在类函数中使用 array_walk
来调用同一类的另一个函数
If I use array_walk
inside a class function to call another function of the same class
class user
{
public function getUserFields($userIdsArray,$fieldsArray)
{
if((isNonEmptyArray($userIdsArray)) && (isNonEmptyArray($fieldsArray)))
{
array_walk($fieldsArray, 'test_print');
}
}
private function test_print($item, $key)
{
//replace the $item if it matches something
}
}
-
警告:
array_walk()
[function.array-walk]:Unable调用test_print()
- 函数不存在于...
Warning:
array_walk()
[function.array-walk]: Unable to calltest_print()
- function does not exist in ...
$ b b
那么,在使用 array_walk()
时,如何指定 $ this-> test_print()
?
答
如果要将类方法指定为回调,则需要指定它所属的对象:
If you want to specify a class method as a callback, you need to specify the object it belongs to:
array_walk($fieldsArray, array($this, 'test_print'));
从手动:
实例化对象的方法作为一个包含索引为0的对象和索引1处的方法名的数组传递。
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
查看http://www.ideone.com/oz3Ma 查看此操作。