我有一个函数:
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”,但是在调用函数时我该如何检查呢?谢谢!
最佳答案
有(在我看来)两种常见的方式:
返回
false
许多内置的 PHP 函数都可以做到这一点使用 SPL exceptions 强>
进化的 PHP 框架(Symfony2、ZF2 等)可以做到这一点
关于php - 从函数返回 "error"的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474168/