【问题标题】:Can I have multiple cases that do the same thing?我可以有多个案例做同样的事情吗?
【发布时间】:2010-09-18 20:28:22
【问题描述】:

第一个肯定是可行的,但下面哪个是有效的方法?

switch($type) {
    case 1:
        print 'success';
    break;

    case 2:
        print 'success';
    break;

    case 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

既然 1、2 和 3 打印都一样,我可以这样做吗?

switch($type) {
    case 1, 2, 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

switch($type) {
    case 1:
    case 2:
    case 3:
        print 'success';
    break;

    case 4:
        print 'success for type 4';
    break;
}

【问题讨论】:

    标签: php switch-statement


    【解决方案1】:

    我同意其他人对以下用途的看法:

    switch ($i) {
       case 0: //drop
       case 1: //drop
       case 2: //drop
          echo "i is 0, 1, or 2";
       break;
       // or you can line them up like this.
       case 3: case 4: case 5:
          echo "i is 3, 4 or 5";
       break;
    }
    

    我要添加的唯一内容是用于多行直通 case 语句的 cmets,这样当您(或其他人)在最初编写代码后查看代码时,您就知道这不是错误。

    【讨论】:

      【解决方案2】:

      PHP 手册为switch 列出了一个示例,例如您的第三个示例:

      <?php
      switch ($i) {
      case 0:
      case 1:
      case 2:
          echo "i is less than 3 but not negative";
          break;
      case 3:
          echo "i is 3";
      }
      ?>
      

      【讨论】:

        【解决方案3】:
         switch($type) 
         {
             case 1:
             case 2:
             case 3:
                 print 'success';
             break;
             case 4:
                 print 'success for type 4';
             break;
         }
        

        是要走的路!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 2010-12-17
          • 2011-04-08
          相关资源
          最近更新 更多