Any way to break if statement in PHP?

前端 未结 20 2024
無奈伤痛
無奈伤痛 2020-12-02 05:05

Is there any command in PHP to stop executing the current or parent if statement, same as break or break(1) for switch/

20条回答
  •  遥遥无期
    2020-12-02 05:27

    proper way to do this :

    try{
        if( !process_x() ){
            throw new Exception('process_x failed');
        }
    
        /* do a lot of other things */
    
        if( !process_y() ){
            throw new Exception('process_y failed');
        }
    
        /* do a lot of other things */
    
        if( !process_z() ){
            throw new Exception('process_z failed');
        }
    
        /* do a lot of other things */
        /* SUCCESS */
    }catch(Exception $ex){
        clean_all_processes();
    }
    

    After reading some of the comments, I realized that exception handling doesn't always makes sense for normal flow control. For normal control flow it is better to use "If else":

    try{
      if( process_x() && process_y() && process_z() ) {
        // all processes successful
        // do something
      } else {
        //one of the processes failed
        clean_all_processes();
      }
    }catch(Exception ex){
      // one of the processes raised an exception
      clean_all_processes();
    }
    

    You can also save the process return values in variables and then check in the failure/exception blocks which process has failed.

提交回复
热议问题