特殊情况下的开关箱


switch case for specific conditions

在下列情况下如何进行切换:

情形1看起来像这样,例如:

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

Case 2看起来像这样,依此类推:

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

函数返回一个布尔值

这可能不是一个好的做法,但我想知道这在开关情况下会是什么样子。

我个人不会在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;
}

要使用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;
}

?>

这似乎不是一个好的做法。Switch主要用于检查单个变量(最常见的是字符串和整数)的值并根据其值执行块。

在你的情况下,当你必须计算布尔类型变量的组合时,最好坚持使用if else。

切换大小写用于语句类似于x=1,而不是x<1的情况。

伪代码:

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 */
    }
}

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

switch($this->hasA() && $this->hasB() && $this->hasC() && $this->hasD()) {
    case true:
        //do true function
    break;
    default:
        //do false function
    break;

}

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