2012-12-20 60 views
3

在下面的代碼中有一段重複的代碼。這可以以另一種方式完成,以便代碼不重複。無論我嘗試什麼,我總是以同樣的方式結束。代碼如下,但生產版本中的代碼更多。這件事情是國家的位置。如何避免在這種情況下重複相同的代碼

if ($GL) 
{ 
echo 'Managed to find your location'; 
}else{ 
echo "Could not identify GL. Please select from the list below."; 
} 

這是整個事情(剝離)。

$GL = false; //GL is detected using ip to location, and returns boolean 
$location = 'UK';//Read from a cookie. 

if(isset($location)) 
{ 
    echo 'We found a cookie with your location<br />'; 

    if(array_key_exists($location,$countries)) 
    { 
     echo 'We found a country in the array. Carrying on<br />'; 
    }else 
    { 
     echo 'Did not find a country in the array. Looking for GL'; 
     if ($GL) 
     { 
      echo 'Managed to find your location. Carrying on'; 
     }else{ 
      echo "Could not identify GL. Please select from the list below."; 
      } 
    } 
} 
else 
{ 
    echo 'Did not find a location cookie<br />'; 

    if ($GL) 
    { 
     echo 'Managed to find your location.Carrying on.'; 
    }else{ 
     echo "Could not identify GL. Please select from the list below."; 
    } 

} 

回答

1

您可以改寫它是這樣的:

  1. 如果位置已通過並在有效的國家/地區列表中找到,請使用該位置。

  2. 如果不是,如果找到GL,則使用它。

  3. 如果一切都失敗,請顯示列表。

在代碼:

if (isset($location) && array_key_exists($location,$countries)) { 
    echo 'We found a country in the array. Carrying on<br />'; 
} elseif ($GL) { 
    echo 'Managed to find your location. Carrying on'; 
} else { 
    echo "Could not identify GL. Please select from the list below."; 
} 
0

你可以使它成爲一個函數,只需使用GL變量調用該函數即可。這種方式,你不必重複相同的,如果一遍又一遍。

3

有幾個簡單的解決方案,你可以做。如:

1)把它放在一個函數:

function validGL($GL) 
{ 
    if ($GL) 
    { 
     echo 'Managed to find your location.Carrying on.'; 
    } 
    else 
    { 
     echo "Could not identify GL. Please select from the list below."; 
    } 
} 

2)存儲一個布爾值,以確定是否有效的位置被發現:

$GL = false; //GL is detected using ip to location, and returns boolean 
$location = 'UK';//Read from a cookie. 

$locationFound = false; 

if(isset($location)) 
{ 
    echo 'We found a cookie with your location<br />'; 

    if(array_key_exists($location,$countries)) 
    { 
     echo 'We found a country in the array. Carrying on<br />'; 

     $locationFound = true; 
    } 
    else 
    { 
     echo 'Did not find a country in the array. Looking for GL'; 
    } 
} 
else 
{ 
    echo 'Did not find a location cookie<br />'; 
} 

if (!$locationFound) 
{ 
    if ($GL) 
    { 
     $GL_msg = 'Managed to find your location. Carrying on'; 
    } 
    else 
    { 
     $GL_msg = "Could not identify GL. Please select from the list below."; 
    } 
} 
+0

嗯......讓我們現在看到的。 – Norman

相關問題