[英]PHP & nested conditions
在PHP中(甚至是其他语言,但在当前情况下,这在PHP中更多),有时我常常不得不编写一些较长的条件,例如以下示例:
我有一个包含许多条件的代码,我想根据某些条件显示不同的结果。
有没有一种方法可以通过使用某种数据结构/配置数组/矩阵/任何方式来正确处理此问题? 也就是说,以某种配置数组或其他形式正确存储这些“条件”和“结果”?
而不是像这样一个很小的示例,但是必须编写一个更大的规模的代码,而不必编写嵌套的条件来支持以后
if (preg_match(/something/, $string) {
$result = 'GREEN';
} elseif (preg_match(/something/, $string) {
$result = 'RED';
} else {
if (something else) {
$result = 'GREEN';
} else {
if (something OR something) {
$result = 'AMBER';
} else {
$result = 'GREEN';
}
}
}
还是处理此问题的唯一方法? 也许一个
if (something and something or something) {
} elseif (something and something and something) {
} elseif (something and something or something and something) {
} etc
谢谢您的帮助
我正在编写一个应根据许多不同数据(该数据的其他属性)针对某些数据显示不同“状态”的应用程序,并且我希望避免代码不可读
出于以下答案的目的,我假设您正在编码OO PHP 。
一个变量
当我有一个确定结果的变量时,如果该变量是布尔值还是接近于布尔值(意味着它只能是一个或两个不同的值),那就像您一样使用if()
语句。 如果变量可以是各种(已知)值(例如您的颜色示例),则可以使用switch()
函数。
两个或多个变量
如果我有两个确定结果的变量,例如颜色和大小,则首先使用switch()
,然后对每个开关使用包含另一个switch()
。
它可能更冗长,但是从长远来看,要跟踪它要容易得多。 以下是该逻辑的简化示例。
switch ($colour) {
case 'red':
red_handler($size);
break;
case 'green':
green_handler($size);
break;
case 'blue':
blue_handler($size);
break;
}
/** We already know the first variable value is red */
function red_handler($size)
{
switch ($size) {
case 'small':
echo "my fruit is a cherry";
break;
case 'medium':
echo "my fruit is an apple";
break;
case 'large':
echo "my fruit is a watermelon";
break;
}
}
您可以使用嵌套数组:
$conditions = [
'/something1/' => [
'/something2/' => "X"
],
'thing3' => [
'/thing3/' => 'Y',
'/thing4/' => 'Z'
]
];
$matched = false;
foreach ($conditions as $key1 => $val1) {
if (preg_match($key1, $string)) {
if (is_array($val1)) {
foreach ($val1 as $key2 => $val2) {
if (preg_match($key2, $string)) {
$result = $val2;
$matched = true;
break;
}
}
} else {
$result = $val1;
$matched = true;
}
}
if ($matched) {
break;
}
}
if (!$matched) {
$result = 'default';
}
要允许任意级别的嵌套,您可以将其转换为递归函数。
与@dearsina相似,我倾向于将其分离为此类事情的功能,例如,如果您知道在很多情况下它可以返回相同的值,例如:
if(isGreen($string)) return 'GREEN';
else if (isRed($string)) return 'RED';
function isGreen($string) {
if(cond1)return true;
if(cond2 && cond3)return true;
if(cond4 || cond 5)return true;
return false;
}
function isRed($string) {
if(cond6)return true;
if(cond1 && cond7)return true;
if(cond2 || cond 8)return true;
return false;
}
我们有时会使用您建议的样式...
if (something and something or something) {
} else if (something and something and something) {
但是您很快就会遇到同样的可读性和维护问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.