Recipe 6.9. Returning Failure


6.9.1. Problem

You want to indicate failure from a function.

6.9.2. Solution

Return false:

function lookup($name) {     if (empty($name)) { return false; }     ... } if (false !== lookup($name)) { /* act upon lookup */ } else { /* log an error */ }

6.9.3. Discussion

In PHP, non-true 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 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.9.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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net