从函数返回"错误"的最佳实践

Jef*_*eff 16 php function

我有一个功能:

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();

     if($row)
          $output = $row['somefield'];
     } else {
          $output = "error";
     }

     return $output;
}

//somewhere on another page...
if(is_numeric($class->CustomerRating()) {
     echo $class->CustomerRating;
} else {
      echo "There is an error with this rating.";
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来查找错误?在这个函数中,如果没有返回任何行,它本身并不意味着"错误",它只是意味着无法计算该值.当我检查函数的结果时,我觉得有一种更好的方法来检查在if函数中显示它之前返回的数据.最好的方法是什么?我想返回一个"假",但是在调用函数时我该如何检查?谢谢!

Flo*_*ent 8

(在我看来)有两种常见方式:

  1. 返回 false
    许多内置的PHP函数都可以做到这一点

  2. 使用SPL异常
    演化的PHP框架(Symfony2,ZF2,...)可以做到这一点

  • @Florent 我如何返回`false` 和错误的解释? (2认同)

Ser*_*min 5

你需要例外

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();
     if ($row !== null) {
          return $row['somefield'];
     } else {
          throw new Exception('There is an error with this rating.');
     }
}

// Somewhere on another page...
try {
    echo $class->CustomerRating();
} catch (Exception $e) {
    echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)