2012-12-20 56 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

相关问题