将函数名称作为回调传递在我的 class 中没有按预期工作

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

这看起来很简单,但是下面的代码给出了以下错误。有什么建议么?

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

我的代码:

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

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

由于您使用 $this->my_array 并且该函数具有关键字 public,我将假设这两个方法在 class 定义中,因此您还必须定义, 你想调用 class 方法而不是普通函数。

这意味着您必须更改:

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

至:

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

您似乎在 class 中有这个,所以有两种方法可以做到这一点。

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

我个人更喜欢闭包的方式,因为这个函数只被这个排序函数使用。

是的,您在 class 中。如何使用class或对象函数进行回调有很多种方法,参见PHP manual。示例:

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