Exit in PHP

Here’s an idiomatic PHP example demonstrating the concept of program exit:

<?php

// Function to be called on script termination
function cleanup()
{
    echo "Cleanup function called.\n";
}

// Register the cleanup function
register_shutdown_function('cleanup');

// This echo will be executed
echo "Starting the script...\n";

// Exit the script with status code 3
exit(3);

// This echo will never be executed
echo "This line will not be reached.\n";

This PHP script demonstrates the concept of exiting a program with a specific status code. Here’s a breakdown of the code:

  1. We define a cleanup function that will be called when the script terminates.

  2. We use register_shutdown_function() to register our cleanup function. This is similar to using defer in some other languages, but it will be called even when using exit().

  3. We echo a message to show that the script has started.

  4. We use the exit() function (which is an alias of die()) to immediately terminate the script with a status code of 3.

  5. The last echo statement will never be executed because the script exits before reaching this line.

To run this script:

  1. Save the code in a file named exit_example.php.
  2. Open a terminal and navigate to the directory containing the file.
  3. Run the script using PHP:
$ php exit_example.php
Starting the script...
Cleanup function called.

To check the exit status:

$ php exit_example.php
Starting the script...
Cleanup function called.
$ echo $?
3

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 to os.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 using exit(). 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.