我正在尝试根据他们的highCharCount对一个单词对象数组进行排序(找到具有highCharCount最高值的单词对象)。出于某种原因,我收到此错误消息:
Warning: usort() expects parameter 2 to be a valid callback, function 'compare' not found or invalid function name in C:\xampp\htdocs\practicePhp\classes.php on line 48
我正在阅读OO PHP usort issue,但我认为它应该对我有用,因为usort和compare函数属于同一个类。我不确定为什么它找不到“比较”。
class SentenceContentContainer {
public $strSentence; //theSentence entered
public $arrayOfWords = []; //words in the sentence
private $num_words_in_sentence;
function __construct($strSentence)
{
$this->strSentence = $strSentence;
$this->arrayOfWords = explode(" ", $strSentence); //get the array of words in the string
$num_words_in_sentence = count($this->arrayOfWords); //count elements in the sentence
}
//function addWordToContainer(&$wordToAdd)
//{
// if($arrayOfWords == null)
// $arrayOfWords = new array[]
// array_push($arrayOfWords, $wordToAdd);
//}
function sortHighestLetterRepeaterOfSentence()
{
if($this->arrayOfWords != null) {
usort($this->arrayOfWords, "compare");
//print it out
foreach ($this->arrayOfWords as $key =>$value) {
echo"$key: $value\n";
}
}
}
function compare($word1, $word2)
{
if ($word1->highCharCount == $word2->highCharCount) {
return 0;
}
return ($word1->highCharCount < $word2->highCharCount) ? -1 : 1;
}
} //SentenceContentContainer