I'm trying to understand the main difference between returning false from a statement as oppose to echoing out an error promoting the user to correct their submission.
Lets take the following function that is used to get the Google Currency Convert API URL and parse in another 3 parameters, $amount, $from, $to
. I use explode
to obtain the numeric values returned within ""
by the API.
function currency_convert($googleCurrencyApi, $amount, $from, $to) {
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$expl = explode('"', $result);
if ($expl[1] == '' || $expl[3] == '') {
return false;
} else {
return array(
$expl[1],
$expl[3]
);
}
}
What is the advantage of returning false if the statement is true compared to echoing out a a constructive message? I see return false regularly used on many forums etc.
Thanks in advance.
Neither, we're in 2012, throw an Exception and handle it in any way you want.
function currency_convert($googleCurrencyApi, $amount, $from, $to) {
$result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
$expl = explode('"', $result);
if ($expl[1] == '' || $expl[3] == '') {
throw new Exception('An error has occured. Describe the error here');
}
return array(
$expl[1],
$expl[3]
);
}
Than, when you call the function:
try { currency_convert($googleApi, $amount, $from, $to) }
catch (Exception $e) { /* Do whatever you want with $e */ }
Read about Exceptions and the try, catch block here
return false
happened.Exceptions are Objects whose Classes can be extended, so you can effectively create multiple types of errors and exceptions such as but not limited to: IllegalArgumentException
, MathException
, FileReadException
, ReallyAwesomeException
, and then handle each differently
try { /* Code Here */ }
catch (IllegalArgumentException $e) { echo 'Illegal Argument!'; }
catch (Exception $e) { echo 'General Error! '. $e->getMessage(); }
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