Exit in PHP
Here’s an idiomatic PHP example demonstrating the concept of program exit:
This PHP script demonstrates the concept of exiting a program with a specific status code. Here’s a breakdown of the code:
We define a
cleanup
function that will be called when the script terminates.We use
register_shutdown_function()
to register our cleanup function. This is similar to usingdefer
in some other languages, but it will be called even when usingexit()
.We echo a message to show that the script has started.
We use the
exit()
function (which is an alias ofdie()
) to immediately terminate the script with a status code of 3.The last echo statement will never be executed because the script exits before reaching this line.
To run this script:
- Save the code in a file named
exit_example.php
. - Open a terminal and navigate to the directory containing the file.
- Run the script using PHP:
To check the exit status:
Key points to note:
- Unlike some compiled languages, PHP scripts don’t need to be compiled before running.
- The
exit()
function in PHP is similar toos.Exit()
in some other languages, allowing you to terminate the script with a specific status code. - PHP’s
register_shutdown_function()
allows you to register functions that will be called on script termination, even when usingexit()
. This is different from some languages where cleanup code might be skipped when forcefully exiting. - In PHP, it’s common to use exit codes to indicate the status of script execution, especially in CLI scripts.
This example demonstrates how to properly exit a PHP script with a status code, which can be useful for error handling and integration with other systems or scripts.