在这种情况下如何避免重复相同的代码

时间:2012-12-20 03:14:36

标签: php

在下面的代码中,有一堆重复的代码。这可以用另一种方式完成,以便代码不会重复。无论我尝试什么,我都会以同样的方式结束。代码如下,但在生产版本中更多。这个东西做国家的位置。

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.";
    }

}

3 个答案:

答案 0 :(得分: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.";
    }
}

答案 1 :(得分:1)

你可以这样改写:

  1. 如果位置已通过并在有效的国家/地区列表中找到,请使用该位置。

  2. 如果没有,如果找到GL,请使用它。

  3. 如果所有其他方法都失败,请显示列表。

  4. 在代码中:

    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.";
    }
    

答案 2 :(得分:0)

你可以使它成为一个函数,只需用GL变量调用该函数。这样,如果一遍又一遍,你就不必重复相同的事情。