【问题标题】:switch case for specific conditions特定条件的开关盒
【发布时间】:2016-09-14 14:26:02
【问题描述】:

以下情况应该如何做switch case:

例如,案例 1 如下所示:

if($this->hasA() && $this->hasB() && $this->hasC() && $this->hasD())
{
  # ....
}

案例 2 可能如下所示:

if($this->hasA() && $this->hasB())
{
  # ....
}

函数返回一个布尔值。

这可能不是一个好习惯,但我想知道这在 switch 案例中会是什么样子。

【问题讨论】:

  • 你必须重组你的函数以使它与开关盒一起工作,例如:switch($this->retrieveABCD()) { case "A" }
  • 一个 switch 通常会有多个 case,你有 1 个。
  • @AbraCadaver 抱歉,我确实有多个案例,我会快速编辑问题

标签: php if-statement switch-statement conditional-statements


【解决方案1】:

我个人不会在if 上这样做,但你可以打开true

switch(true) {
    case $this->hasA() && $this->hasB() && $this->hasC() && $this->hasD():
        //code
        break;

    case $this->hasA() && $this->hasB():
        //code
        break;
}

请记住,函数是针对每种情况执行的($this->hasA()$this->hasB() 在上面的代码中两次),所以如果它们很昂贵(复杂的查询、文件加载等),那么你最好运行它们一次,然后多次检查结果。

如果任何案例共享一些代码,那么您将按顺序构建它,而不是使用break,这样一个案例就会执行到下一个案例。从您的示例中不清楚是否有一些通用代码。

一个简单的例子:

switch(true) {
    case $this->hasA():
        //code

    case $this->hasB():
        //case above may or may not execute
        //more code

    case $this->hasC():
        //one or both cases above may or may not execute
        //more code
        break;
}

【讨论】:

  • 谢谢,你还是更喜欢 if 语句而不是 switch 正确吗?
  • 用你的简单例子是的。如果它更复杂,并且可以通过在案例之间共享来提高可读性并减少代码,那么我可能会使用 switch,但可能不会。
【解决方案2】:

这作为一个开关会很尴尬;如果你必须这样做,我会像这样设置为布尔值:

switch($this->hasA() && $this->hasB() && $this->hasC() && $this->hasD()) {

    case true:
        //do true function
    break;

    default:
        //do false function
    break;


}

只有布尔类型的排列是可能的,因为所有 4 个$this->has() 条件都为真,或者如果 1 为假,则整个条件为假。

【讨论】:

    【解决方案3】:

    要使用 switch 语句,您需要将四个布尔变量组合成一个变量,例如

    <?php
    
    $a = 1;
    $b = 0;
    $c = 1;
    $d = 1;
    $str = $a.$b.$c.$d;
    
    switch($str){
    case('0000'):
      echo('Case 1: '.$str);
      break;
    case('0001'):
      echo('Case 2: '.$str);
      break;
    //...
    case('1111');
      echo('Case 16: '.$str);
      break;
    }
    
    
    ?>
    

    【讨论】:

      【解决方案4】:

      我似乎不是一个好习惯。 Switch 主要用于当您想要检查单个变量(最常见的是字符串和整数)的值并根据其值执行块时。

      在您必须评估布尔类型变量的组合时,最好坚持使用 if else。

      【讨论】:

        【解决方案5】:

        switch case 用于语句类似于 x=1,而不是 x

        伪代码:

        if (x = 1) {
        /*code*/
        }
        
        /*vs*/
        
        switch (x) {
            case 1 {
                /*code*/
            }
        }
        
        /*and for the x<1 value,*/
        
        if (x < 1) {
            /* code */
        }
        switch(True) {
            case (x < 1) {
                /* code */
            }
        }
        

        【讨论】:

        • 注意:我是在 golang 中完成的。 Golang 很容易理解,你可以明白我的意思。根据您的意愿将这些转换为 PHP。
        猜你喜欢
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-03
        • 2023-01-09
        相关资源
        最近更新 更多