简体   繁体   English

PHP和嵌套条件

[英]PHP & nested conditions

in PHP (and even other languages but in the present case this is more for PHP), i often end up sometimes having to code long conditions such as the example below: 在PHP中(甚至是其他语言,但在当前情况下,这在PHP中更多),有时我常常不得不编写一些较长的条件,例如以下示例:

i have a code with many conditions and i want to display a different result based on certain conditions. 我有一个包含许多条件的代码,我想根据某些条件显示不同的结果。

  • if something is RED and the other thing is RED, then print X, 如果某物是红色而另一物是红色,则打印X,
  • if something is RED but the other thing is BLACK, then print Y 如果某物是红色但另一物是黑色,则打印Y
  • if something RED and the other thing is RED but a third thing is blue, then print X 如果某物为红色而另一物为红色,但第三物为蓝色,则打印X
  • & so on 等等

is there a way to properly handle this by using some kind of data structure/configuration array/matrix/whatever ? 有没有一种方法可以通过使用某种数据结构/配置数组/矩阵/任何方式来正确处理此问题? that is, storing these "conditions" and "results" properly in some kind of configuration array or other ? 也就是说,以某种配置数组或其他形式正确存储这些“条件”和“结果”?

instead of having to code nested conditions that can be tricky to support afterwards like this very small example but in a much bigger scale 而不是像这样一个很小的示例,但是必须编写一个更大的规模的代码,而不必编写嵌套的条件来支持以后

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';
    }
  }
}

or is it the only way of handling this ? 还是处理此问题的唯一方法? maybe with a single 也许一个

if (something and something or something) {

} elseif (something and something and something) {

} elseif (something and something or something and something) {

} etc

thank you for your help 谢谢您的帮助

i'm coding an app that should display a different "status" for a certain data depending on many different data (other attributes of this data), and i'd like to avoid having unreadable code 我正在编写一个应根据许多不同数据(该数据的其他属性)针对某些数据显示不同“状态”的应用程序,并且我希望避免代码不可读

For the purposes of the answer below I'm assuming you're coding OO PHP . 出于以下答案的目的,我假设您正在编码OO PHP

One variable 一个变量

When I have one variable that determines the outcome, if the variable is boolean or close to being boolean (meaning it can only either be one or two different values), is to use an if() statement like you have. 当我有一个确定结果的变量时,如果该变量是布尔值还是接近于布尔值(意味着它只能是一个或两个不同的值),那就像您一样使用if()语句。 If the variable can be a variety of (known) values, like your colours example, I use a switch() function. 如果变量可以是各种(已知)值(例如您的颜色示例),则可以使用switch()函数。

Two or more variables 两个或多个变量

If I have two variables that determine the outcome, for instance colour and size, I first use a switch() , then for each switch, I use a method that contains another switch() . 如果我有两个确定结果的变量,例如颜色和大小,则首先使用switch() ,然后对每个开关使用包含另一个switch()

It may be more verbose, but it is so much easier to keep track of in the long run. 它可能更冗长,但是从长远来看,要跟踪它要容易得多。 Below is a simplified example of the logic. 以下是该逻辑的简化示例。

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

You can use nested arrays: 您可以使用嵌套数组:

$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';
}

To allow arbitrary levels of nesting you could turn this into a recursive function. 要允许任意级别的嵌套,您可以将其转换为递归函数。

In a similar vein to @dearsina i'd tend to separate it out into functions for this kind of thing, for example if you know there are lots of cases where it could return the same value, eg: 与@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;
}

we do sometimes use the style you've suggested... 我们有时会使用您建议的样式...

if (something and something or something) {

} else if (something and something and something) {

but you can quickly end up back in the same problems of readability and maintenance issues 但是您很快就会遇到同样的可读性和维护问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM