2013-03-06 39 views
2
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; 
    } 
} 

我得到以下警告:PHP uasort在OOP

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. 

而且第五百五十四行包含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 
+2

uasort($ posts_array,數組($此, 'CMP')); – realization 2013-03-06 10:16:23

回答

5

如果> = 5.3和你不使用其他任何功能比較方法,你也可以使用封:

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

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

使用PHP 5.3.1 – 2013-03-06 10:27:30

+0

@IstiaqueAhmed只是很好然後:) – 2013-03-06 10:28:01

+0

@IstiaqueAhmed它工作嗎? – 2013-03-07 00:21:44

6

你要這樣稱呼它:

uasort($posts_array, Array ($this, 'cmp'); 

以下鏈接說明了如何構建一個PHP中有效回調:http://www.php.net/manual/en/language.types.callable.php

+0

+1爲了提供回調定義的鏈接 – 2013-03-06 10:19:09

+0

@MarkBaker,請參閱我的編輯。 – 2013-03-06 10:23:06

+0

您使用的是什麼版本的PHP? – 2013-03-06 10:25:08

5
uasort($posts_array, array($this, 'cmp')); 
+0

請參閱我的編輯 – 2013-03-06 10:22:48

+1

您是不是在靜態調用DBNews :: get_latest_posts()? – 2013-03-06 10:25:58

+0

非靜態調用 – 2013-03-06 10:51:38