PHP继续内部功能 [英] PHP continue inside function

查看:92
本文介绍了PHP继续内部功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能非常微不足道,但我一直无法弄清楚。

这样做:

  function MyFunction(){

//做东西

}


foreach($ x as $ y){

MyFunction() ;

if($ foo ==='bar'){continue;}

//做东西

echo $输出。 <峰; br>;

}

但这不是:

 函数MyFunction(){

//做东西

if($ foo === 'bar'){continue;}

}


foreach($ x as $ y){

MyFunction();

//做东西

echo $输出。 <峰; br>;


$ / code $ / pre
$ b $ p只产生1 $输出然后:

 致命错误:无法打破/继续1级

任何想法我做错了什么?

解决方案

你不能破/继续一个函数外的循环,来自一个函数内部。然而,你可以基于函数的返回值来打破/继续循环:

  function myFunction(){
//做东西
返回$ foo ==='bar';


$ b foreach($ x as $ y){
if(myFunction()){
continue;
}

//做东西

echo $输出。 <峰; br>;
}


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?

解决方案

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:

function myFunction(){   
    //Do stuff
    return $foo === 'bar';
}


foreach($x as $y) {
    if(myFunction()) {
        continue;
    }

    //Do stuff

    echo $output . '<br>';    
}

这篇关于PHP继续内部功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆