我有一个功能:
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
演进的PHP框架(Symfony2,ZF2,...)就是这样做的使用例外。避免从函数和方法返回错误
我会使用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();
}
- 节省混乱。
试试这个:
try {
$myvar = CustomerRating();
//do something with it
} catch (Exception $e) {
echo $e->getMessage();
}
如果您返回零,这将确保它不会中断。
虽然返回false表示错误在PHP库中很常见,但有几个缺点:
我在工作中看到的另一种方法是返回一个包含正常结果和可能错误的数组,基本上返回一对,但是为了获得真实的结果,你必须从数组中检索它,这是更令人不快的代码写入
异常是对这个问题的完全成熟的解决方案,但是为简单错误编写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;
}