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

后端 未结 3 1217
星月不相逢
星月不相逢 2020-12-03 04:45

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

class user
{
   public function getUserFields($userIdsArr         


        
相关标签:
3条回答
  • 2020-12-03 04:55

    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'])
    }
    
    0 讨论(0)
  • 2020-12-03 04:59

    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 讨论(0)
  • 2020-12-03 05:13

    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');
    
    0 讨论(0)
提交回复
热议问题