函数中的语句永远不会评估为真

时间:2015-12-29 06:28:28

标签: php

$button=$_GET['button'];    

function read2On(){
  $myFile = "light state.txt";
  $fh = fopen($myFile, 'r');
  $theData = fread($fh, filesize($myFile));
  fclose($fh);
  if($theData!="light is ON"){
    sleep(1);
    read2On();
  }
  else if($theData=="light is ON"){
    echo $theData;
  }
}

function read2Off(){
  $myFile = "light state.txt";
  $fh = fopen($myFile, 'r');
  $theData = fread($fh, filesize($myFile));
  fclose($fh);
  if($theData!="light is OFF"){        
    sleep(1);
    read2Off();
  }
  else if($theData=="light is OFF"){
    echo $theData;
  }
}

if($button=="lightTurnOn"){
  lightTurnOn();
  read2On();
}
else if($button=="lightTurnOff"){
  lightTurnOff();
  read2Off();
}

函数read2On()被调用并按我的预期执行,但函数read2Off不是。函数体中的语句永远不会计算为true,因此函数除了从第一次调用时的值为true时,才会无限地调用self。对于完整性函数ligthTurnOff(),如果语句作为函数read2Off()被调用并正确执行,则从相同的else调用。应该在哪里出问题?

1 个答案:

答案 0 :(得分:0)

文件大小($ myFile)的值被缓存,因此fread()将错误的字符数分配给$ theData。调用clearstatcache()解决了这个问题。