我注意到您确实可以在 switch 语句中使用 continue
关键字,但在 PHP 上它并没有达到我的预期。
如果 PHP 失败了,谁知道还有多少其他语言也失败了?如果我经常在语言之间切换,如果代码的行为不像我预期的那样,这可能是个问题。
我应该避免在 switch 语句中使用 continue
吗?
PHP (5.2.17) 失败:
for($p = 0; $p < 8; $p++){
switch($p){
case 5:
print"($p)";
continue;
print"*"; // just for testing...
break;
case 6:
print"($p)";
continue;
print"*";
break;
}
print"$p\r\n";
}
/*
Output:
0
1
2
3
4
(5)5
(6)6
7
*/
C++ 似乎按预期工作(跳转到 for 循环的末尾):
for(int p = 0; p < 8; p++){
switch(p){
case 5:
cout << "(" << p << ")";
continue;
cout << "*"; // just for testing...
break;
case 6:
cout << "(" << p << ")";
continue;
cout << "*";
break;
}
cout << p << "\r\n";
}
/*
Output:
0
1
2
3
4
(5)(6)7
*/
最佳答案
尝试使用 continue 2
继续围绕 switch 语句的循环的下一次迭代。
编辑:
$foo = 'Hello';
for ($p = 0; $p < 8; $p++) {
switch($p) {
case 3:
if ($foo === 'Hello') {
echo $foo;
break;
} else {
continue 2;
}
default:
echo "Sleeping...<br>";
continue 2;
}
echo "World!";
break;
}
//这将打印:
sleep ...
sleep ...
sleep ...
世界你好!
关于php - 我应该在 switch 语句中使用 continue 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12349826/