How do I use a class method as a callback function?

喜夏-厌秋 提交于 2019-11-27 01:46:01

问题


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
  }

}

It gives me the following error -

Warning: array_walk() [function.array-walk]: Unable to call test_print() - function does not exist in ...

So, how do I specify $this->test_print() while using array_walk()?


回答1:


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

From the manual:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.




回答2:


If you need to call a static method without instantiating the class you could do so:

// since PHP 5.3
array_walk($fieldsArray, 'self::test_print');

Or from outside:

// since PHP 5.5
array_walk($fieldsArray, User::class.'::test_print');



回答3:


To call a class method as a callback function in another class method, you should do :

public function compareFucntion() {
}

public function useCompareFunction() {
  usort($arrayToSort, [$this, 'compareFucntion'])
}


来源:https://stackoverflow.com/questions/3840294/how-do-i-use-a-class-method-as-a-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!