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

萝らか妹 提交于 2019-11-28 07:11:39
Daniel Vandersluis

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.

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

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