Passing function name as callback doesn't work as expected in my class

1.1k views Asked by At

This seems straightforward, but the below code is giving the following error. Any suggestions?

usort() expects parameter 2 to be a valid callback, function 'cmp' not found or invalid function name

My code:

function cmp($item1, $item2) {
    return strcmp(strtolower($item1->last_name), strtolower($item2->last_name));
}

public function get_people() {
    usort($this->my_array, 'cmp');
}
3

There are 3 answers

0
Rizier123 On BEST ANSWER

Since you use $this->my_array and the function has the keyword public, I'm going to assume these two methods are in a class definition, so you also have to define, that you want to call a class method and not a normal function.

This means you have to change:

usort($this->my_array, 'cmp');

to:

usort($this->my_array, [$this, 'cmp']);
                      //^^^^^ So it will call the class method and not a normal global function
0
Jonathan On

It seems you have this within a class so there's two ways you can do this.

first way, by telling it the method exists on the current class

public function get_people() {
    usort($this->my_array, array($this, 'cmp'));
}

second way, using closures

public function get_people() {
    usort($this->my_array, function($item1, $item2) {
        return strcmp(strtolower($item1->last_name), strtolower($item2->last_name));
    });
}

I personally prefer the closure way as this function is only used by this sort function.

0
steffen On

Yes, you're inside a class. There are many ways how to use class or object functions for callback, see PHP manual. Example:

  public function get_people() {
      usort($this->my_array, array($this, 'cmp'));
  }