跳回到开关语句之外


Jumping back outside of a switch statement

我想知道如何在满足某种情况时跳回到 switch 语句之外,因为代码将不得不重试它刚刚完成的操作。这是我的代码示例;

$result = $this->check($user, $password); 
switch($result){
    case 'invalid-email-password':
        //Do stuff
        break;
    case 'error':
        //Do stuff
        //Jump back to $result = $this->check to try again
        break;

仅当"错误"情况不再是 $this->check() 函数的结果时,代码才应继续。

一般来说,如果你想编程一个"重试直到它工作"的事情,请考虑以下因素:

while(true) {
    doSomething();
    if( $it_worked) break;
}

请注意,由于您处于 switch 语句中,因此您需要在成功结果上使用 break 2; 才能退出switchwhile

为了防止无限循环,您可以有一个$attempts计数器,该计数器会在尝试次数用完时手动倒计时并中断循环。