将goto替换为while循环?

时间:2014-07-07 14:04:05

标签: php loops error-handling goto

我正在使用goto如果有任何错误,它会在顶部重新开始。

我也不能在函数中使用goto跳出函数。

我知道goto很糟糕,但while循环如何适合我的代码?

例如:

$ch = curl_init();

retry:

$result = curlPost($ch, "home.php", http_build_query($arg));

if (strpos($postResult, "Welcome") !== false) {
    sleep(10);
    goto retry;
}

$sql = "SELECT * FROM data";
$q = mysql_query($sql) or die(mysql_error());

while($row =  mysql_fetch_assoc($q)) {
    $name['something'] = $row['name'];
    submitData($ch,$name);
}


function submitData($ch,$name) {

    $result2 = curlPost($ch, "submit.php", http_build_query($name));

    if (strpos($postResult, "Website close") !== false) {
        sleep(10);
        goto retry; //goto wouldnt work.
    }

   // do something here
}

1 个答案:

答案 0 :(得分:1)

基本上,你会有这样的事情:

$success = false;
while(!$success) {
    // do stuff here
    // psuedocode follows:
    if failure {
        continue; // skip remainder of `while` and retry
    }
    if complete {
        $success = true; // loop will end
        // or "break;" to exit loop immediately
    }
}

请注意,如果您的"如果失败"它本身就在一个循环中,你需要continue 2;。或者,如果您处于嵌套循环中,continue 3;等等。