OOP中的php uasort [英] php uasort in OOP

查看:79
本文介绍了OOP中的php uasort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我收到以下警告:

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.

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

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

Where to make use of the string or array and in what way?

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

EDIT : If I use uasort($posts_array, array($this, 'cmp'));, I get the following warning:

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

推荐答案

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

If you have >= 5.3 and you're not using the compare method in any other function, you can also use closures:

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

    return ($a < $b) ? -1 : 1;
});

这篇关于OOP中的php uasort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆