php将文件内容读取到静态数组中


php Read file content to a static array

我正在为贝叶斯过滤器编写代码。对于一个特定的单词,我想检查该单词是否在停止单词列表中,我从电脑上的文件中从停止单词列表填充。因为我必须对很多单词这样做,所以我不想一次又一次地从电脑上读取StopWord文件。

我想做一些类似的事情

function isStopWord( $word ){
       if(!isset($stopWordDict))
       {
           $stopWords = array();
           $handle = fopen("StopWords.txt", "r");
           if( $handle )
           {
               while( ( $buffer = fgets( $handle ) ) != false )
               {
                   $stopWords[] = trim( $buffer );
               }
           }
           echo "StopWord opened";
           static $stopWordDict = array();
           foreach( $stopWords  as $stopWord )
               $stopWordDict[$stopWord] = 1;
       }
      if( array_key_exists( $word, $stopWordDict ) )
           return true;
      else
          return false;
  }

我认为使用静态变量可以解决问题,但事实并非如此。请帮忙。

将静态声明放在函数的开头:

function isStopWord( $word ){
   static $stopWordDict = array();
   if(!$stopWordDict)
   {
       $stopWords = file("StopWords.txt");
       echo "StopWord opened";
       foreach( $stopWords  as $stopWord ) {          
           $stopWordDict[trim($stopWord)] = 1;
       }
   }
  if( array_key_exists( $word, $stopWordDict ) )
       return true;
  else
      return false;
}

这将起作用,因为空数组被认为是伪造的。