Error handling is a critical part of PHP development. If not managed properly, errors can crash applications or lead to data loss. To help with this, PHP provides several built-in functions for error management—error_get_last() being one of the most practical ones.
error_get_last() is a native PHP function used to retrieve information about the most recent error. It returns an associative array that contains the error type, message, file, and line number, making it easier for developers to identify and resolve issues.
Using error_get_last() is simple. You just call it after an error has occurred. Often, it’s used alongside a try-catch block or within custom error handling logic to retrieve error details for logging or debugging.
try {
$result = 1 / 0; // Division by zero triggers a PHP warning
} catch (Exception $e) {
// Exception handling logic
}
$error = error_get_last();
if ($error) {
echo 'Error Type: ' . $error['type'] . '<br>';
echo 'Error Message: ' . $error['message'] . '<br>';
echo 'In File: ' . $error['file'] . '<br>';
echo 'On Line: ' . $error['line'] . '<br>';
}
In this example, dividing by zero triggers a warning. While the try-catch structure does not catch warnings, you can still retrieve the error using error_get_last() right afterward. This allows you to handle or log the issue based on the detailed information returned.
When called, error_get_last() returns an associative array with the following keys, if an error occurred:
For a full list of error types and their corresponding integer values, refer to the official PHP documentation.
There are a few things to keep in mind when using error_get_last():
error_get_last() is a highly useful function for handling non-fatal errors in PHP. It allows developers to access detailed error information and respond accordingly. When used in combination with other error handling techniques, it can significantly enhance debugging efficiency and code stability, making it a must-know for every PHP developer.