gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:04:42 25 4
gpt4 key购买 nike

在下面的代码中有一段代码会 self 重复。这可以用另一种方式完成,这样代码就不会重复吗?无论我尝试什么,我总是以同样的事情结束。代码在下面,但在生产版本中更多。这个东西做国家定位。

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) 放在一个函数中:

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) 存储一个 bool 值以确定是否找到了有效位置:

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

关于php - 在这种情况下如何避免重复相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13964745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com