我有一段代码可以计算给定.txt文件中的单词,但由于某些原因,我收到以下错误,但没有给出结果。我不明白什么是错的:
Warning: arsort() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/test-php-oop/class.wordcounter.php on line 20
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/test-php-oop/class.wordcounter.php on line 21
<?php // index.php
include_once("class.wordcounter.php");
$wc = new WordCounter("words.txt");
$wc->count(WordCounter::DESC);
?>
<?php //class.wordcounter.php
class WordCounter {
const ASC = 1;
const DESC = 2;
private $words;
function __contruct($filename) {
$file_content = file_get_contents($filename);
$this->words = (array_count_values(str_word_count(strtolower($file_content),1)));
}
public function count($order) {
if ($order == self::ASC)
asort($this->words);
else if ($order == self::DESC)
arsort($this->words);
foreach ($this->words as $key => $val)
echo $key . " = " . $val . "<br/>";
}
}
?>
答案 0 :(得分:2)
我发现了这个错误,__construct
方法拼错了!
以下是更正后的代码并且有效:
<?php // index.php
include_once("class.wordcounter.php");
$wc = new WordCounter("words.txt");
$wc->count(WordCounter::DESC);
?>
<?php //class.wordcounter.php
class WordCounter {
const ASC = 1;
const DESC = 2;
private $words;
function __construct($filename) {
$file_content = file_get_contents($filename);
$this->words = (array_count_values(str_word_count(strtolower($file_content),1)));
}
public function count($order) {
if ($order == self::ASC)
asort($this->words);
else if ($order == self::DESC)
arsort($this->words);
foreach ($this->words as $key => $val)
echo $key . " = " . $val . "<br/>";
}
}
?>
答案 1 :(得分:0)
看起来脚本无法获取指定的文件。请尝试使用绝对URL,并告诉我它是否有效。
更改此行:
$wc = new WordCounter("http://your_domain/your_path/words.txt");
答案 2 :(得分:0)
你确定file_get_contents()
实际上是在回复吗?仅仅因为你看到文件并不意味着PHP肯定可以访问它。
答案 3 :(得分:0)
试试这个,
<?php
$no_of_words = 0;
str_replace(" ","",file_get_contents("/filename.txt"),$no_of_words);
echo $no_of_words;
?>