Handling Errors Returned by Functions


Many times, if there's been an error in a function, that function returns a value of FALSE intentionally. Not only are many built-in PHP functions designed this way, but you can also write your own functions to do the same, as in this case where we're calculating reciprocals and return a value of FALSE if we're asked for the reciprocal of 0:

 function reciprocal($value) {     if ($value != 0) {         return 1 / $value;     }     else {         return FALSE;     } } 

One way of handling a value of FALSE returned from a function indicating there's an error is to use the PHP die function, the same as the PHP exit function. You pass this function a message, and it ends the script, displaying that message.

For example, the PHP fopen function opens files, as we discuss in Chapter 7, "Object-Oriented Programming and File Handling." If it can't open a fileas when the file can't be foundit returns a value of FALSE. You can use the PHP operator to try to open the file or quit using the die (or exit) function this way:

 <?php     $filename = "nonexistent_data_file";     $file = fopen($filename, "r")         or die("Cannot open file $filename. Does it exist?"); ?> 

Here's what you see when you try to open a non-existing filefirst you see PHP's warning, and then the text echoed by the die function:

 PHP Warning:  fopen(nonexistent_data_file): failed to open stream: No such file or     directory in C:\php\t.php on line 3 Cannot open file nonexistent_data_file. Does it exist? 

That's it for our coverage of functions in this chapter. In the next chapter, we're going to start bringing everything together by creating web pages into which the user can enter data that we can read. For many developers, this is the very heart of PHP.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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