2013-02-12 72 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; 
    } 
}