PHP continue 函数内部
这可能非常微不足道,但我一直无法弄清楚。
这有效:
function MyFunction(){
//Do stuff
}
foreach($x as $y){
MyFunction();
if($foo === 'bar'){continue;}
//Do stuff
echo $output . '<br>';
}
但这不行:
function MyFunction(){
//Do stuff
if($foo === 'bar'){continue;}
}
foreach($x as $y){
MyFunction();
//Do stuff
echo $output . '<br>';
}
只产生 1 $ 输出,然后:
Fatal error: Cannot break/continue 1 level
知道我做错了什么吗?
This is likely very trivial but I haven't been able to figure it out.
This works:
function MyFunction(){
//Do stuff
}
foreach($x as $y){
MyFunction();
if($foo === 'bar'){continue;}
//Do stuff
echo $output . '<br>';
}
But this doesn't:
function MyFunction(){
//Do stuff
if($foo === 'bar'){continue;}
}
foreach($x as $y){
MyFunction();
//Do stuff
echo $output . '<br>';
}
That yields only 1 $output and then:
Fatal error: Cannot break/continue 1 level
Any idea what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法从函数内部中断/继续函数外部的循环。但是,您可以根据函数的返回值中断/继续循环:
You can't break/continue a loop outside a function, from within a function. However, you can break/continue your loop based on the return value of your function:
continue
语句在循环结构内有效仅有的。The
continue
statement is valid inside looping structures only.continue
只能跳过循环结构内的迭代。在函数内部,在循环内运行的上下文会丢失。
continue
can only skip iterations inside of a looping structure.Inside of your function, the context of it being ran inside a loop is lost.
该函数是单独编译的,可以从任何地方调用。因此,这里使用 continue 没有任何意义,因为上下文不在循环中。如果您希望将工作委托给此处的函数,则应该将该函数设计为返回一些是否
继续
的指示,例如TRUE
或FALSE
返回值。The function is compiled separately and could be called from anywhere. Thus, the use of
continue
makes no sense here as the context is not in that of a loop. If you wish to delegate work to a function here, you should design the function to return some indication of whether tocontinue
or not, such as aTRUE
orFALSE
return value.