我即将使用goto语句

时间:2011-09-28 20:23:08

标签: php

让我免于猛禽死亡 - 有没有更好的方法来处理这种结构?

while(condition) {
    $this->phase1();
    $this->phase2();
    $this->phase3();
    $this->phase4();
}

在其中任何一种方法中,都可以满足条件。满足条件后 IMMEDIATELY ,循环必须退出。例如,如果我可以在break;内调用phase2();,我就不需要goto语句(当然,这会引发错误)。

8 个答案:

答案 0 :(得分:11)

返回一个布尔值来执行每个阶段,直到成功。

while (condition) {
    if ($this->phase1() || $this->phase2() || $this->phase3() || $this->phase4()) {
        // Success!
    }
}

答案 1 :(得分:7)

或者您可以使用State pattern

总之,不要使用goto语句,而是更改$this的内部状态,以便方法phase1phase2phase3phase4具有没有效果,是空功能。因为它们将是空函数,所以你将飞过它们并退出循环!

您可能还需要一些事件或Observer模式,以了解何时更改状态。

答案 2 :(得分:4)

从不同的阶段返回一个布尔值。如果不成功,我会返回false,然后检查并break

答案 3 :(得分:2)

抛出异常......听起来很特别......

try {
    while(condition) {
        $this->phase1();
        $this->phase2();
        $this->phase3();
        $this->phase4();
    }
} catch (Exception $e) { }

答案 4 :(得分:0)

如何在if中包装每个阶段:

while(condition)
{
  if(condition)
  {
    $this->phase1();
  }

  if(condition)
  {
    $this->phase2();
  }

  if(condition)
  {
    $this->phase3();
  }

  if(condition)
  {
    $this->phase4();
  }
}

当然,通过一些规划和循环,这可能会变得更加紧凑。

答案 5 :(得分:0)

一种方法可能是使用if()语句检查每个phase*()的返回值并打破while循环。

这样的事情:

while (condition)   {
    if ($this->phase1())   { break; }
}

答案 6 :(得分:0)

请不要使用goto语句,请考虑编写代码库的编码器

如果你的条件不是太多的开销,你可以

while(*condition*){
    $this->phase1();
    if (*condition*){
       $this->phase2();
    }

    ...

} 

答案 7 :(得分:0)

$phases=array('phase1','phase2','phase3','phase4');
foreach($phases as $phase){
    $this->$phase();
    if(condition)break;
}

此外,如果您想从函数内部突破,可以使用异常。