Specifications

Terminating Execution: die and exit
So far in this book we have used the language construct exit to stop execution of a script. As
you probably recall, it appears on a line by itself, like this:
exit;
It does not return anything.
For a slightly more useful termination, we can use die(). This language construct can be
used to output an error message or execute a function before terminating a script. This will be
familiar to Perl programmers.
You can use it on its own, in a similar way to
exit:
die(“Script ending now”);
More commonly it is ored with a statement that might fail, such as opening a file or connect-
ing to a database:
mysql_query($query) or die(“Could not execute query”);
Instead of just printing an error message, you can call one last function before the script
terminates:
function err_msg()
{
echo “MySQL error was: “;
echo mysql_error();
}
mysql_query($query) or die(err_msg());
This can be useful as a way of giving the user some reason why the script failed.
Alternatively, you could email yourself so that you know if a major error has occurred, or add
errors to a log file.
Serialization
Serialization is the process of turning anything you can store in a PHP variable or object into a
bytestream that can be stored in a database or passed along via an URL from page to page.
Without this, it is difficult to store or pass the entire contents of an array or object.
It has decreased in usefulness since the introduction of session control. Serializing data is prin-
cipally used for the types of things you would now use session control for. In fact, the session
control functions serialize session variables in order to store them between HTTP requests.
Advanced PHP Techniques
P
ART IV
450
26 7842 CH21 3/6/01 3:41 PM Page 450