php - 从函数返回 "error"的最佳实践

标签 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.";
}

是否有更好的查找错误的方法?在这个函数中,如果没有返回任何行,这本身并不意味着“错误”,它只是意味着无法计算该值。当我检查一个函数的结果时,我觉得有更好的方法来检查返回的数据,然后再将它显示在 if 函数中。最好的方法是什么?我想返回一个“false”,但是在调用函数时我该如何检查呢?谢谢!

最佳答案

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

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

  2. 使用 SPL exceptions
    进化的 PHP 框架(Symfony2、ZF2 等)可以做到这一点

关于php - 从函数返回 "error"的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474168/

相关文章:

php - 在 PHP 中返回一个方法

php - Laravel 4 一对一关系

php - Laravel 5 - 将一个表的查询与另一个查询进行比较

php - Google 是唯一需要 "identifier_select"的 OpenID 提供商吗?

c++ - 什么是函数客户端?

typescript - 具有多种类型的函数声明

php 对象运算符 -> 没有实例?

php - 需要帮助使用 PHP 将关联数组转换为嵌套 JSON

php - 函数参数列表中的赋值运算符(=)?

c - 传递指针数组 c