PHP Functions
Returning Failure
Problem
You want to indicate failure from a function.Solution
Return false:function lookup($name) {
if (empty($name)) { return false; }
/* ... */
}
$name = 'alice';
if (false !== lookup($name)) {
/* act upon lookup */
} else {
/* log an error */
}
Discussion
In PHP, nontrue values aren’t standardized and can easily cause errors. As a result, your functions should return the defined false keyword because this works best when checking a logical value.Other possibilities are '' or 0. However, while all three evaluate to nontrue inside an if, there’s actually a difference among them. Also, sometimes a return value of 0 is a meaningful result, but you still want to be able to also return failure.
For example, strpos() returns the location of the first substring within a string. If the substring isn’t found, strpos() returns false. If it is found, it returns an integer with the position. Therefore, to find a substring position, you might write:
if (strpos($string, $substring)) { /* found it! */ }
However, if $substring is found at the exact start of $string, the value returned is 0. Unfortunately, inside the if, this evaluates to false, so the conditional is not executed. Here’s the correct way to handle the return value of strpos():
if (false !== strpos($string, $substring)) { /* found it! */ }
No comments:
Post a Comment