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

问题描述 投票:16回答:7

我有一个功能:

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函数中显示它之前返回的数据。最好的方法是什么?我想返回一个“假”,但是在调用函数时我该如何检查?谢谢!

php function
7个回答
8
投票

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

  1. 返回qazxsw poi 许多内置的PHP函数都是这样做的
  2. 使用false 演进的PHP框架(Symfony2,ZF2,...)就是这样做的

3
投票

使用例外。避免从函数和方法返回错误


2
投票

0
投票

我会使用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(); } - 节省混乱。


0
投票

处理错误的最佳方法是抛出异常。这样你可以有各种不同的错误并相应地处理它们。

你可以这样做:

exceptions

0
投票

试试这个:

try {
    $myvar = CustomerRating();
    //do something with it
} catch (Exception $e) {
    echo $e->getMessage();
}

如果您返回零,这将确保它不会中断。


0
投票

虽然返回false表示错误在PHP库中很常见,但有几个缺点:

  1. 您无法返回有关错误的说明
  2. 如果false值是函数的有效返回值,则不能使用此方法

我在工作中看到的另一种方法是返回一个包含正常结果和可能错误的数组,基本上返回一对,但是为了获得真实的结果,你必须从数组中检索它,这是更令人不快的代码写入

异常是对这个问题的完全成熟的解决方案,但是为简单错误编写try ... catch块有点麻烦。对于记录为抛出异常的函数,如果在调用它时没有捕获异常,PhpStorm会抱怨这一点,因此在我看来,异常更好地保留用于更严重的错误

返回结果和可能错误的一种方法是使用pass by reference参数,该参数在Objective C中使用很多

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

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

     return $output;
}

//somewhere on another page...
if($class->CustomerRating() !== false) {
     echo $class->CustomerRating();
} else {
     echo "There is an error with this rating.";
}

如果你不关心错误,你可以调用函数省略错误参数

/**
 * get element from array
  * @param $index int
  * @param $list array
  * @param $error object
  */
function getFromArray($index, $list, &$error=null) {
    if ($index >= 0 && $index < count($list)) {
        return $list[$index];
    }

    $error = "out of index";
    return null;
}

$list = ['hello', 'world'];

$error = null;
$result = getFromArray(-1, $list, $error);
if ($error) {
    echo "an error occurred " . $error;
} else {
    echo $result;
}
© www.soinside.com 2019 - 2024. All rights reserved.