我注意到您确实可以在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
*/发布于 2012-09-10 18:35:10
PHP 7.3或更高版本:
不建议使用continue中断switch语句,这将触发警告。
要退出switch语句,请使用break。
要继续执行当前switch语句周围的循环的下一次迭代,请使用continue 2。
PHP 7.2或更早版本:
continue和break可以在PHP的switch语句中互换使用。
发布于 2012-10-22 22:13:19
尝试使用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;
}//This will print: Sleeping... Sleeping... Sleeping... Hello World!
发布于 2012-09-10 18:36:58
The documentation for the PHP continue statement清楚地说明了这点:
注意:请注意,对于continue而言,在PHP语句中被视为循环结构。
您应该知道,不同的语言赋予相同的关键字微妙不同的含义,而不是假设PHP continue的行为与C++ continue相同。
如果continue在PHP switch中有意义,而它在C++中不起作用,那么一定要使用它。
如果continue在C++ switch中有意义,而它在PHP中不起作用,那么一定要使用它。
https://stackoverflow.com/questions/12349826
复制相似问题