有什么办法可以打破PHP中的if语句? [英] Any way to break if statement in PHP?

查看:120
本文介绍了有什么办法可以打破PHP中的if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中是否有任何命令停止执行当前或父if语句,与switch/loopbreakbreak(1)相同.例如

Is there any command in PHP to stop executing the current or parent if statement, same as break or break(1) for switch/loop. For example

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

echo "finish";

上面的代码中的

PHP将不会执行echo "test";并将转到echo "finish";

in the above code PHP will not do echo "test"; and will go to 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";

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

I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?

更新:在发布此问题仅两年后,我长大了,我学会了如何以小块形式编写代码,为什么嵌套(如果嵌套的话)可能会散发出代码的味道,以及如何避免此类问题的发生,通过编写可管理的小型函数排在第一位.

Update: Just 2 years after posting this question, I grew up, I learnt how code can be written in small chunks, why nested if's can be a code smell and how to avoid such problems in the first place by writing manageable, small functions.

推荐答案

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

Don't worry about other users comments, I can understand you, SOMETIMES when developing this "fancy" things are required. If we can break an if, a lot of nested ifs won't be necessary, making the code much more clean and aesthetic.

此示例代码说明,证明在某些情况下中断if可能比许多丑陋的嵌套ifs更适合... 如果您没有面对某些情况并不意味着它不存在.

This sample code illustrate that CERTAINS SITUATIONS where breaked if can be much more suitable than a lot of ugly nested ifs... if you haven't faced that certain situation does not mean it doesn't exists.

丑陋的代码

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();

}

美观代码

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

就像@NiematojakTomasz所说的那样,使用goto是替代方法,这的坏处是您总是需要定义标签(点目标).

As @NiematojakTomasz says, the use of goto is an alternative, the bad thing about this is you always need to define the label (point target).

这篇关于有什么办法可以打破PHP中的if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆