Php 更好的错误处理方法?

Php 更好的错误处理方法?,php,class,error-handling,Php,Class,Error Handling,错误处理的最佳方式是什么?这就是我想到的: class test { public static function Payment($orderid, $total) { if (empty($orderid) && empty($total)) { return array('status' => 'fail', 'error' => 'Missing Data'); } } } 我听说过

错误处理的最佳方式是什么?这就是我想到的:

class test {

    public static function Payment($orderid, $total) {
        if (empty($orderid) && empty($total)) {
            return array('status' => 'fail', 'error' => 'Missing Data');
        }
    }

}

我听说过Try/异常,但如何将其融入我的代码中?如果你能提供的例子,这将是伟大的

如果使用PHP 5,则可以处理异常错误:


这种方式比手动设置异常消息更干净,因为您可以访问try-catch系统,并且可以隔离异常处理

我倾向于抛出异常,然后使用try/catch机制来处理后果。手册页在这里:

最佳实践是使用异常

然而,在您发布的用例中,只需在控制器级别进行检查就足够了

我还认为显式检查数组的返回类型(失败时)是违反直觉的

如前所述,使用。具体到您的示例,如果某个条件失败,您将抛出一个异常。然后,当您调用可以引发异常的方法时,可以使用
try/catch
处理块将其包装起来

class test {
  public static function Payment( $orderid, $total ) {
    if (empty( $orderid ) && empty( $total )) {
        throw new Exception('Missing Data');
    }
  }
}


try {
  test::Payment("1", "2"); //should be fine
  test::Payment(); //should throw exception
} catch (Exception $e){
  echo $e;
  //do other things if you need 
}

下面是如何修改代码以使用异常。它还有助于记录引发异常的环境

class test {

    /**
     * [method description]
     * @throws Exception if the order ID or total is empty
     */
    public static function Payment($orderid, $total) {
        if (empty($orderid) && empty($total)) {
            throw new Exception("fail: Missing Data");
        }
    }

}
如果希望在异常中包含额外数据,还可以创建自己的异常类

class MyException extends Exception{
  public $status, $error;
  public function __construct($status, $error){
    parent::__construct("$status: $error");
    $this->status = $status;
    $this->error = $error;
  }
}

谢谢你的样品。。测试:支付(“1”、“2”);将在控制器文件中。这将如何工作?@user622378只需将整个try/catch块放在控制器文件中即可。我只是把它放在课堂之外,以演示它的用法。