从内部函数调用结束函数 - PHP

End function from inner function call - PHP

我有一个需要多次检查的函数,为此,我添加了多个函数,但是当某些内部函数失败时,它需要 return 响应失败,但它没有并继续下一个内部函数-函数

 public static function doMultipleWorks(){

  self::checkFirstCondition();
  self::checkSecondCondition();

  ...
  ...

  return response(['status' => true, 'data' => [...]]);

 }

 public static function checkFirstCondition(){

  ....
  ....
  if(this != that){
    return response(['status' => false, 'error_msg' => 'this is not equal to that']]
  }

 }

 public static function checkSecondCondition(){

  ....
  ....
  if(this != that){
    return response(['status' => false, 'error_msg' => 'this is not equal to that']]
  }


 }

问题是,如果第一个或第二个函数失败,它仍然会继续并且不会中断函数。任何帮助将不胜感激。

您没有检查 checkFirstcheckSecond 的 return 值,这样做或抛出异常以中断函数和 try/catch 异常

public function foo() {
     if ($bar = $this->bar()) return $bar;
}

public function bar() {
   if (something) return resp;
}

public function foo() {
    try {
        $this->bar();
    }catch(\Exception $e) {
         return [ 'success' => false, 'status' => $e->getMessage(), ];
    }
}

public function bar() {
   if (something) throw new Exception('Fail');
}

您需要检查功能的响应并根据响应,您应该继续或中断进一步的进程。我相信你应该这样做:

public static function doMultipleWorks(){

  $firstResponse = self::checkFirstCondition();
  if ($firstResponse['status'] == false) {
       return $firstResponse;
  }
  $secondResponse = self::checkSecondCondition();
  if ($secondResponse['status'] == false) {
       return $secondResponse;
  }

  ...
  ...

  return response(['status' => true, 'data' => [...]]);

 }

 public static function checkFirstCondition(){

  ....
  ....
  if(this != that){
    return response(['status' => false, 'error_msg' => 'this is not equal to that']]
  }

 }

 public static function checkSecondCondition(){

  ....
  ....
  if(this != that){
    return response(['status' => false, 'error_msg' => 'this is not equal to that']]
  }


 }

希望它能帮助你修正你的方法。