Recipe 6.10 Returning Failure
6.10.1 Problem
You want to indicate failure from a
function.
6.10.2 Solution
Return false:
function lookup($name) {
if (empty($name)) { return false; }
...
}
if (false !== lookup($name)) { /* act upon lookup */ }
6.10.3 Discussion
I
n PHP, non-true values aren't
standardized and can easily cause errors. As a result,
it's best if all your functions 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 non-true 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! */ }
Also, false is always guaranteed to be
false — in the current version of PHP and forever more. Other
values may not guarantee this. For example, in PHP 3,
empty('0') was true, but it
changed to false in PHP 4.
6.10.4 See Also
The introduction to Chapter 5 for more on the
truth values of variables; documentation on strpos(
) at http://www.php.net/strpos and
empty( ) at
http://www.php.net/empty; information on
migrating from PHP 3 to PHP 4 at
http://www.php.net/migration4.
|