Php 重新启动if-else构造

Php 重新启动if-else构造,php,Php,让我们看一下以下代码: if ($a == 1) { echo "this is stage 1"; } else if ($a == 2) { echo "this is stage 2"; } else if ($a == 3) { $a = 1; // at this point I want something that restarts the if-else construct so // that the output will be "t

让我们看一下以下代码:

if ($a == 1) {
    echo "this is stage 1";
} 
else if ($a == 2) {
    echo "this is stage 2";
}
else if ($a == 3) {
    $a = 1;
    // at this point I want something that restarts the if-else construct so
    // that the output will be "this is stage 1"
}
我现在正在研究if-else构造,假设我有三个阶段,if-else构造检查我处于哪个阶段


现在,第三阶段的一些活动会导致跳回第一阶段。现在我已经传递了第一阶段的代码,这就是为什么我想以某种方式重新启动if-else构造。有办法吗?更重要的是:有没有更好的方法来做我想做的事?因为我的想法似乎不是很好的实践。

简短的回答是肯定的,有办法,但更好的答案是肯定的,你的第二个问题也是

至少,放在一个函数中可以从多个位置调用的代码中。比如说,

function stageOneCode() {
    //do stuff;
}
等等。。我会为每个阶段推荐一个函数,但是如果没有看到在各个阶段执行的内容,就很难提出建议


在任何情况下,在第三阶段函数结束时,只需调用第一阶段函数。

递归函数对此很有帮助(但如果它总是返回到1,则可能会有过大的杀伤力)

或:


使用。您可以有一个“默认”案例以及特定案例。

您是对的,这是一个不好的做法

你是在要求

例如:

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
那可能也不是你想要的


您可能只想将代码抽象为函数,并在必要时多次调用它们。

您可以在if周围进行无休止的循环,如果完成了,则可以中断

while (1) {
    if ($a == 1) {
        echo "this is stage 1";
        break;
    } 
    else if ($a == 2) {
        echo "this is stage 2";
        break;
    }
    else if ($a == 3) {
        $a = 1;
    }
    else {
        break;
    }
}

也许你想看看这个问题,你正在搜索的是一个循环:


如果switch()不能满足您的需要,这是我的第二个想法+1我认为循环不是一个好的解决方案。也许我误解了这个问题,但这里似乎没有重复任务。OP希望一次执行一个特定数量的代码,在执行一组不同的代码后可能会发生,也可能不会发生<代码>中断在这样使用时只是一个花哨的
Goto
。当$a不是1、2或3时,它也会变得毛茸茸的。现在,他的代码没有任何作用。对于循环,它会挂起,所以至少他需要添加一个带中断的默认案例,我想,这同样只是包装一个
Goto
。我实际上也在考虑循环。问题在于,在每个阶段中,该阶段可能会切换到下一个或上一个阶段。现在,每个阶段中都有某些代码(不是全部),当阶段更改为该阶段时,必须执行这些代码。因此,我可以围绕if-else构造进行2次循环,以捕捉这个阶段的变化。。。。。。哦,但是如果阶段没有改变,它会重复我的阶段代码。我得想一想…@user1601869如果你不想重复,那就说出来。请查看更新的答案。如果($a==1 | |$a==3),你就不能使用
?当然在这种情况下我可以。但我戏剧性地简化了情况。我也这么想,这就是为什么我把它作为一个评论…+1作为建议
goto
的答案+我认为这是一个非常糟糕的练习!最后一个+1表示“如果不知道你想做什么,就很难提出更好的方法”。
<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
switch ($a) {

 case 3:
    // Execute 3 stuff
    // No break so it'll continue to 1
 case 1:
   // Execute 1 stuff
   break // Don't go any further
 case 2:
    // 2 stuff
    break; 


}
while (1) {
    if ($a == 1) {
        echo "this is stage 1";
        break;
    } 
    else if ($a == 2) {
        echo "this is stage 2";
        break;
    }
    else if ($a == 3) {
        $a = 1;
    }
    else {
        break;
    }
}
// initialize $a 
$a = 1;

// the while loop will return endless
while (true);

    // if you want to break for any reason use the 
    // break statement:

    // if ($whatever) {
    //    break;
    // }

    if ($a == 1) {
        echo "this is stage 1";
    }
    else if ($a == 2) {
        echo "this is stage 2";
    }
    else if ($a == 3) {
        $a = 1;
        // continue will go back to the head 
        // of the loop (step 1) early:
        continue;
    }

    // don't forget to increment $a in every loop
    $a++;
}