如何使用类方法作为回调函数? [英] How do I use a class method as a callback function?

查看:306
本文介绍了如何使用类方法作为回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在类函数中使用 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 call test_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 查看此操作。

这篇关于如何使用类方法作为回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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