2017-10-05 22 views
1

我有幾個圈,並希望當我用休息來指定一個特定的循環或繼續進行指示繼續進行或中斷特定環路

PHP doc,它是寫,我可以使用數字數字參數來它有多少嵌套的封閉結構將被分解出來。

$i = 0; 
while (++$i) { 
    switch ($i) { 
    case 5: 
     echo "At 5<br />\n"; 
     break 1; /* Exit only the switch. */ 
    case 10: 
     echo "At 10; quitting<br />\n"; 
     break 2; /* Exit the switch and the while. */ 
    default: 
     break; 
    } 
} 

,但我想一些更友好的是這樣的:

$i = 0; 
loop1: // Label/tag of loop1 
while (++$i) { 
    loop2: // Label/tag of loop2 
    switch ($i) { 
    case 5: 
     echo "At 5<br />\n"; 
     break loop2; /* Exit only the switch. */ 
    case 10: 
     echo "At 10; quitting<br />\n"; 
     break loop1; /* Exit the switch and the while. */ 
    default: 
     break; 
    } 
} 

這可能嗎?

+1

我會建議,而不是中斷使用goto語句來跳轉你的代碼向上或向下,這將是更容易。 –

+2

不要使用'goto'! [這是爲什麼!](https://stackoverflow.com/questions/1900017/is-goto-in-php-evil) –

+0

你可以使用不推薦轉到[http://php.net/manual/fr/control -structures.goto.php](PHP 5> = 5.3.0,PHP 7),在while循環結束時使用標籤(loopend :)。 – okante

回答

2

這是不可能的。此外,太多的break-語句會使您的代碼非常難讀,難以理解。您應該重構您的代碼以避免breaks並使用其他control flow statements

do { 
    $i += 1; 
    if($i === 5) { 
     echo "At 5<br />\n"; 
    } else if ($i === 10) { 
     echo "At 10; quitting<br />\n"; 
    } 
} while($i < 10); 

您還可以嘗試將代碼拆分爲不同的函數或方法。

function doSomething($i) { 
    if($i === 5) { 
     echo "At 5<br />\n"; 
    } else if ($i === 10) { 
     echo "At 10; quitting<br />\n"; 
    } 
} 

function run() { 
    $i = 0; 
    while($i < 10) doSomething(++$i);  
} 

在第二種情況下,您必須意識到兩個函數之間的強烈依賴關係。如果您要更改run()以便它計數到15,那麼如果$i = 10功能doSomething將會行爲不當。因此,您應該將它們封裝到一個類中,或者嘗試引入另一個變量,這兩個函數都可以用來確定循環何時結束。這將避免未來的錯誤和魔術事件發生。

function doSomething($i, $max) { 
    if($i === 5) { 
     echo "At 5<br />\n"; 
    } else if ($i === $max) { 
     echo "At 10; quitting<br />\n"; 
    } 
} 

function run($max) { 
    $i = 0; 
    while($i < $max) doSomething(++$i);  
} 

當然是使用一個,兩個甚至更多breaks如果你的代碼保持可讀沒問題。但你應該考慮是否有其他更優雅的方法來解決你的問題。主要有更好的方法。

1

我個人的建議是將嵌套循環代碼提取到單獨的方法和/或使用例外。一般來說,「打破標籤」感覺就像是「轉到」。我不想讓你被恐龍吃掉;)

1

我不相信這是可能的,但如果你分解你的代碼,並把嵌套循環放入函數中,你可以使用return來退出所有循環。這可能會提高可讀性。