简体   繁体   中英

how to break loop from nested function?

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文简体   中文繁体   中英对照 版本,有任何建议请联系yoyou2525@163.com。

Heres the problem

public function loop (){
    while($this->controlFunction()){
        //do stuff
    }
}
public function controlFunction (){
     $this->nestedFunction();
}

public function nestedFunction (){
   if($condA){ //whatsoever the condition
       break;
   } 
}

Is that possible ? I dont wanna return and then use a flag to return back again, seems like spaghetti code

Thanks for the answer guys, after thought, my question seems quite stupid though... Anyways thank you :)

2 anwsers

As per the documentation :

break ends execution of the current for, foreach, while, do-while or switch structure

as calling a function changes the scope, the break statement will have no effect on the previous scope executing the while -loop.

In fact, because the scope is different than in the nestedFunction method, calling break will result in a fatal error ( E_ERROR ) because that scope is not aware of the while -loop running in the previous scope.

Fatal error: Cannot break/continue 1 level

So no, it is not possible.

Have you tried it yet? Regardless, returning a value is a better approach for clarity of what the function is supposed to do. You should always try to make functions independent, it is good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question
 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM