有没有办法打破PHP中的if语句?

Muh*_*man 119 php

是否有任何PHP命令停止执行当前或父if陈述,相同breakbreak(1)switch/ loop.例如

$arr=array('a','b');
foreach($arr as $val)
{
  break;
  echo "test";
}

echo "finish";
Run Code Online (Sandbox Code Playgroud)

在上面的代码PHP将不会做echo "test";,将去echo "finish";

如果我需要这个

$a="test";
if("test"==$a)
{
  break;
  echo "yes"; // I don't want this line or lines after to be executed, without using another if
}
echo "finish";
Run Code Online (Sandbox Code Playgroud)

我想要上面breakif声明并停止执行echo "yes";或不再需要执行的代码,可能有或可能没有附加条件,有没有办法做到这一点?

Age*_*nce 206

不要担心其他用户的评论,我可以理解你,有时开发这种"花哨"的东西是必需的.如果我们可以打破if,那么就不需要很多嵌套ifs,使代码更加干净和美观.

这个示例代码说明了CERTAINS SITUATIONS如果可以比许多丑陋的嵌套ifs更合适...... 如果你没有遇到某种情况并不意味着它不存在.

丑陋的代码

if(process_x()) {

    /* do a lot of other things */

    if(process_y()) {

         /* do a lot of other things */

         if(process_z()) {

              /* do a lot of other things */
              /* SUCCESS */

         }
         else {

              clean_all_processes();

         }

    }
    else {

         clean_all_processes();

    }

}
else {

    clean_all_processes();

}
Run Code Online (Sandbox Code Playgroud)

好看的代码

do {

  if( !process_x() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_y() )
    { clean_all_processes();  break; }

  /* do a lot of other things */

  if( !process_z() )
    { clean_all_processes();  break; }

  /* do a lot of other things */
  /* SUCCESS */

} while (0);
Run Code Online (Sandbox Code Playgroud)

正如@NiematojakTomasz所说,使用goto是另一种选择,关于这一点的坏处是你总是需要定义标签(点目标).

  • 大!有时问题由于其深刻的意识而被误解.你完美得到它,我需要干净的代码,以避免跟踪`if`的结尾 (27认同)
  • @rdlowrey,谈话是免费的,所以请向我们展示一个解决OP问题的"写得好的OOP"的例子:3 (8认同)
  • 不要将样本的请求与个人攻击混淆......事实上,你遗漏了一些重要的东西,并非所有的编码都应该是OOP,用OOP的魔法*编写简单的任务是一件疯狂的事情. (7认同)
  • 我需要在每次成功测试(大约3或4次测试)后执行相同的代码,并在每次失败的测试中放置一个`elseif`.这正是我正在寻找的,现在我的代码是KISS和DRY兼容:)谢谢! (4认同)
  • 男人这感觉很脏!但它得到了我的upvote ..我正在研究一个肮脏的系统;) (3认同)
  • 如果你需要这样做......好吧......你做错了,你需要重构。可读性并不是通过滥用语言结构“侵入”代码的东西;这是编写良好的代码的不言而喻的副产品。 (2认同)
  • 删除所有其他内容并将 `clean_all_processes()` 放在最后。 (2认同)

Max*_*sky 93

将代码封装在函数中.您可以随时停止执行某个功能return.

  • @ arnaud576875如果代码在函数中,则可以在if语句中使用return来中断执行. (3认同)
  • 我虽然你想要一个if,而不是一个函数?;) (2认同)

Rah*_*jan 38

正确的方法:

try{
    if( !process_x() ){
        throw new Exception('process_x failed');
    }

    /* do a lot of other things */

    if( !process_y() ){
        throw new Exception('process_y failed');
    }

    /* do a lot of other things */

    if( !process_z() ){
        throw new Exception('process_z failed');
    }

    /* do a lot of other things */
    /* SUCCESS */
}catch(Exception $ex){
    clean_all_processes();
}
Run Code Online (Sandbox Code Playgroud)

在阅读了一些评论后,我意识到异常处理并不总是对正常的流量控制有意义.对于正常的控制流程,最好使用"If else":

try{
  if( process_x() && process_y() && process_z() ) {
    // all processes successful
    // do something
  } else {
    //one of the processes failed
    clean_all_processes();
  }
}catch(Exception ex){
  // one of the processes raised an exception
  clean_all_processes();
}
Run Code Online (Sandbox Code Playgroud)

您还可以将过程返回值保存在变量中,然后检查失败/异常块哪个进程失败.

  • 在这种情况下,异常可能很有用,但似乎您滥用了它们。异常是异常的,不适用于正常的程序流程。如果失败是异常的,那么 process_x-z 应该自己抛出异常;clean_all_processes() 在finally 块中会更好,因为它是清理的,无论如何都必须完成。 (2认同)

Mar*_*ler 17

因为你可以打破 do/while循环,让我们" "一轮.最后一段时间(假),条件永远不会成立,也不会重复.

do
{
    $subjectText = trim(filter_input(INPUT_POST, 'subject'));
    if(!$subjectText)
    {
        $smallInfo = 'Please give a subject.';
        break;
    }

    $messageText = trim(filter_input(INPUT_POST, 'message'));
    if(!$messageText)
    {
        $smallInfo = 'Please supply a message.';
        break;
    }
} while(false);
Run Code Online (Sandbox Code Playgroud)

  • 整洁的方法 - 完成工作。 (2认同)

Nie*_*asz 15

转到:

跳转操作符可以用来跳转到计划中的其他部分.目标点由标签后跟冒号指定,指令以goto后跟所需的目标标签.这不是完全不受限制的转到.目标标签必须位于同一个文件和上下文中,这意味着您不能跳出函数或方法,也不能跳到一个.您也无法跳转到任何类型的循环或切换结构.你可以跳出这些,一个常见的用途是使用goto代替多级休息 ......

  • 每次你使用`goto`,小耶稣都会吃一只小猫.另外,http://xkcd.com/292/ (80认同)
  • 对不起,保持一致.我参考了php手册页,解释了所提到的关键字的确切用法.即使它是肮脏的解决方案,它仍然是正确的解决方案. (11认同)
  • 不用担心,程序员总是会让你觉得你没有正确编码,并希望我们像他们一样编码.在php社区中更是如此,因为我们是一群时髦的编码员,PHP为我们提供了这些自由关键词以及对每个人如何做事情的判断的自由.我在生产代码中使用了(不是广泛的)`goto`关键字,我从来没有遇到过麻烦. (5认同)
  • 我不完全明白这样做不好的做法?它比所有其他解决方案简单得多? (3认同)

T.T*_*dua 6

使用GOTO命令.

if(smth) {
   .....
   .....
   .....
   .....
   .....
   goto Area1;
   .....
   .....


}



Area1:
....your code here....
Run Code Online (Sandbox Code Playgroud)

但是,请记住goto非常不推荐的做法.


Stp*_*ane 5

不,没有办法像循环内那样“破坏” if块。:(
因此,将您的测试变成一个switch

我想知道为什么没有人鼓励您使用switch语句,因为(即使您没有很多测试用例)
您是否认为它太冗长?

我一定会去这里

  switch($a){
    case 'test':
        # do stuff here ...
        if(/* Reason why you may break */){
           break; # this will prevent executing "echo 'yes';" statement
        }
        echo 'yes';  # ...           
        break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
    # default:
        # something else here  ..
        # break;
  }
Run Code Online (Sandbox Code Playgroud)

对我来说,异常是指引发错误,而不是真正控制执行缺陷。
如果您尝试设置的中断行为与意外错误无关,则异常处理不是此处的正确解决方案:/

  • @Stphane 迟到的评论,但在这种情况下使用 switch 违反了最少惊讶的原则。switch 语句应该控制数据的选择,而不是控制程序流。 (2认同)

小智 5

$a = 1;

switch($a) {

  case "1":

    if  ($condition1){
      break;
    }

    if  ($condition2){
      break;
    }

    if  ($condition3){
      break;
    }
}
Run Code Online (Sandbox Code Playgroud)

就这样我得到了我想要的。我使用 switch 只有一个确定的情况,然后使用 break 来选择 if 条件。我使用 break 的原因:condition1 和 condition2 可能都满足,在那种情况下只应用 condition1 .IF 根据顺序是有选择性的。

  • 你不需要变量。只需使用`switch(true) { case true:` (8认同)

Ult*_*EVV 5

你可以使用do-while(false):

    <?php
    do if ($foo)
    {
      // Do something first...

      // Shall we continue with this block, or exit now?
      if ($abort_if_block) break;

      // Continue doing something...

    } while (false);
    ?>
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/control-structures.if.php#90073中所述


Oli*_*rth 1

不。

但怎么样:

$a="test";
if("test"==$a)
{
  if ($someOtherCondition)
  {
    echo "yes";
  }
}
echo "finish";
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是,我正在寻找一个更简单的版本,以避免太多“if”语句 (3认同)
  • @Usman:如果您有多个条件,那么您需要检查它们。传统上,检查条件涉及“if”语句。我不确定您希望如何避免这种情况。 (2认同)