php 如何使用类方法作为回调函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3840294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:17:18  来源:igfitidea点击:

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

phpoopcallbackarray-walk

提问by Sandeepan Nath

If I use array_walkinside a class function to call another function of the same class

如果我array_walk在一个类函数内部使用来调用同一个类的另一个函数

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 ...

警告: array_walk()[function.array-walk]:无法调用 test_print()- 函数不存在于 ...

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

那么,我$this->test_print()在使用时如何指定array_walk()

回答by 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.

实例化对象的方法作为数组传递,该数组包含索引 0 处的对象和索引 1 处的方法名称。

回答by Klesun

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

回答by Denise Ignatova

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'])
}