Terminating PHP |
| Written by phpecho.com | |||
There are a couple of functions in PHP which help us to terminate execution of the PHP script. These are the exit and die functions. We will study these functions in details in this tutorial. Terminating functions are used mainly for two reasons but before we discuss that, it is critical to understand how PHP script parsing works with respect to these two functions. Whenever the functions die or exit is intercepted, the script execution is abandoned without even parsing further. These functions terminate further processing abruptly. One way the exit or die functions are used is to terminate the script when all useful information has been sent to the client. This way, the script does not need to worry about closing out all branches and similar activity. This obviously is not the best use for these constructs as using them for this purpose makes the code very difficult to read and understand. A better use for these constructs is to use them for error handling. For example, suppose you are doing an operation and you get an error. It makes more sense to identify the possible exception and terminate the script. The terminated script should then display a relevant error message. For example, consider this code: <?php
$con = $get_DB_Connection();
if (!$con){
die ("Failed to get DB Connection");
}
// continue using the connection
?>
In the above case, if there is a problem getting the database connection, then there is no point proceeding with the execution of the script. The die construct will abruptly terminate execution and send the error message "Failed to get DB Connection" to the browser. If there is no problem with the database, then script execution will proceed. Now let us look at the syntax for both of these constructs. The exit construct takes a string or a number as input, prints out the argument and then terminates. So, if your code snippet is - <?php
echo ("Printing line one..<br>");
exit(2);
echo ("Printing line two..");
?>
The out put for this code snippet would be: Printing line one.. The die construct is an exact replica of the exit construct - so the syntax is also the same. Some people prefer to use the die construct because it somehow makes more literal sense to refer a call to terminate a script as die instead of exit.
|