I have a 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.";
}
Is there a better way to find errors? In this function, if no rows are returned, it doesn't mean an "error" per se, it simply means the value can't be calculated. When I check for the result of a function, I feel like there is a better way to check the data being returned before I display it in the if function. What's the best way to do this? I'd like to return a "false", but how would I check for that when calling the function? Thanks!
There are (in my opinion) 2 common ways:
Returning false
Many builtin PHP functions do that
Using SPL exceptions
Evolved PHP frameworks (Symfony2, ZF2, ...) do that
You need exceptions:
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();
}
Use exceptions. Avoid returning errors from functions and methods
Although returning false to indicate an error is prevalent in PHP libraries, there are several drawbacks:
Another approach I see in my job is to return an array with both the normal result and the possible error, basically returning a pair, but then to get the real result you have to retrieve it from the array which is more unpleasant code to write
Exceptions are a full fledged solution to this problem but it's a bit cumbersome to write the try...catch block for simple errors. For a function that's documented to throw an exception, if you don't catch the exception when you call it, PhpStorm will complain about that, so in my opinion exceptions are better reserved for more severe errors
One way to return both the result and a possible error is to use a pass by reference parameter, which is used a lot in Objective C
/**
* 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;
}
if you don't care about the error, you can just call the function leaving out the error parameter
echo getFromArray(0, $list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With