2013-02-12 57 views
0

我想在平民黄昏时关闭我们的冲浪网络摄像头,但在代码底部的if语句中遇到了一些困难。我很确定这是一个语法问题,但看不到它。如果语句语法和逻辑问题

//Sunrise 
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise 
$sunrise = date_sunrise(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0); 
$sunrise = (integer) str_replace(":", "", $sunrise); 
// echo "Sunrise: ".$sunrise."</br>"; 

//Sunset 
//Set Zenneth to 96 which is Civilian Twilight start. Normally set to 90 for "normal" sunrise 
$sunset = date_sunset(time(), SUNFUNCS_RET_STRING, 51.575363, -4.037476, 96, 0); 
$sunset = (integer) str_replace(":", "", $sunset); 
// echo "Sunset: ".$sunset."</br>"; 


// get the current date using a 24 digit hour without leading zeros, as an int 

$current_time = (Integer) date('Gi'); 

if ((($current_time >= 0000 && $current_time <= $sunrise) && ($current_time >= $sunset 
&& $current_time <= 2359)) && ($_SERVER["REQUEST_URI"] == "/webcams/langland-webcam" 
| $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam" || $_SERVER["REQUEST_URI"] == 
"/webcams/llangennith-webcam" || $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam")) 
{ 
    // Cameras are offline 

    return true; 

} 

回答

1

哎呀。这是一个巨大的if声明。我打破它一点:

if (
    (
      ($current_time >= 0000 && $current_time <= $sunrise) 
     && ($current_time >= $sunset && $current_time <= 2359) 
    // ^^ Should be `||` 
    ) && (
      $_SERVER["REQUEST_URI"] == "/webcams/langland-webcam" 
     | $_SERVER["REQUEST_URI"] == "/webcams/caswell-webcam" 
    //^Should be `||` 
     || $_SERVER["REQUEST_URI"] == "/webcams/llangennith-webcam" 
     || $_SERVER["REQUEST_URI"] == "/webcams/swansea-webcam" 
    ) 
) { 

至于评论,第一件事我注意到:你应该第一个比较使用||。此外,您稍后使用单个管道|而不是||。总之,我建议你重构一下这段代码。也许将允许的URI移动到一个数组中,然后使用in_array()来检查它。繁琐的if像这样可能会导致问题 - 正如你刚刚发现的那样。像这样:

$validUris = array("/webcams/langland-webcam", "/webcams/caswell-webcam", "/webcams/llangennith-webcam", "/webcams/swansea-webcam"); 
if (in_array($_SERVER["REQUEST_URI"], $validUris)) { 
    if (($current_time >= 0000 && $current_time <= $sunrise) || ($current_time >= $sunset && $current_time <= 2359)) { 
     // Cameras 
     return true; 
    } 
}