Я пытаюсь отсортировать массив словесных объектов в соответствии с их 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
Я читал о проблеме с USort OO PHP, но я думаю, что это должно работать для меня, так как функция usort и сравнения находятся в одном классе. Я не уверен, почему он не может найти «сравнить».
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
[$this, 'method']
как таковой:usort($this->arrayOfWords, [$this, 'compare'])
. Если вы используете его вне класса, используйтеusort($instance->arrayOfWords, [$instance, 'compare'])
и убедитесь, что функция общедоступна. - person h2ooooooo   schedule 09.05.2016usort($this->arrayOfWords, array($this, 'compare'));
предупреждение? Вам все еще нужно передать массив, который сообщаетusort()
, что функция находится в контексте класса$this
. - person WillardSolutions   schedule 09.05.2016