PHP 函数错误处理并在 foreach 循环进入变量时返回


PHP Function error handling and returning when foreach loop goes on a variable

*关于如何在PHP面向对象编码中处理这种类型的问题的问题/困惑*

我有客户

类,我需要暂停客户的服务,但是当客户有服务的待处理工作类型时,我需要为调用函数返回一个 false 来执行错误句柄(我不能在这里这样做,因为它可能是电子邮件、输出或 html)

但是我很困惑如何处理这个问题,好像使用以下代码它只会在 foreach 循环的最后一个条件下返回 false,我想,关于如何在编码角度处理这个问题的任何想法

 /**
   * return false on failier 
   * Customer suspend all services for this customer
   * 
   */
  public function suspendServices(){
    $pending=false; 
    foreach ($this->services() as $service) {
    $pending = $service->hasPendingWorktypes();
    if($pending === true) {
        return false;
    }   
    $service->state()->changeTo(8);  
    }//end of foreach services 
  }//end of function

Exceptions 非常适合这项工作。然后,调用服务的业务方法可以有效地处理该部分以获得正确的结果。

public function suspendServices(){
    $pending=false; 
    foreach ($this->services() as $service) {
    $pending = $service->hasPendingWorktypes();
    if($pending === true) {
        throw new PendingExcpetion(); //Throw the exception
    }   
    $service->state()->changeTo(8);  
    }//end of foreach services 
}