在OOP中的php uasort

Ist*_*med 2 php sorting

class DBNews {

    public function get_latest_posts($limit){

        // code goes here

        $posts_array = array();
        uasort($posts_array, $this->cmp);

    }

    public function cmp($a, $b) {
        if ($a == $b) {
            return 0;
        }

        return ($a < $b) ? -1 : 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下警告:

Warning: uasort() expects parameter 2 to be a valid callback, 
no array or string given in 
C:\xampp\htdocs\news\admin\functions.php on line 554.
Run Code Online (Sandbox Code Playgroud)

并且第554行包含uasort($posts_array, $this->cmp).

在哪里使用字符串或数组以及以什么方式?

编辑:如果我使用uasort($posts_array, array($this, 'cmp'));,我收到以下警告:

uasort() expects parameter 2 to be a valid callback,
array must have exactly two members in
C:\xampp\htdocs\news\admin\functions.php on line 554
Run Code Online (Sandbox Code Playgroud)

Jan*_*čič 8

你必须这样称呼它:

uasort($posts_array, Array ( $this, 'cmp');
Run Code Online (Sandbox Code Playgroud)

以下链接说明了如何在PHP中构建有效的回调:http://www.php.net/manual/en/language.types.callable.php


Mar*_*ker 5

uasort($posts_array, array($this, 'cmp'));
Run Code Online (Sandbox Code Playgroud)


Ja͢*_*͢ck 5

如果你有> = 5.3并且你没有在任何其他函数中使用compare方法,你也可以使用闭包:

uasort($posts_array, function($a, $b) {
    if ($a == $b) {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
});
Run Code Online (Sandbox Code Playgroud)