← Back to PHP Course | Chapter 13: Error Handling | Lesson 1 of 5

PHP Error Handling Introduction

Types of Errors in PHP

PHP distinguishes several error severities: notices flag minor issues like an undefined variable, warnings report bigger problems without halting execution, and fatal errors stop the script immediately -- knowing which is which shapes how urgently you need to react.

Example: Types of Errors in PHP

php
<?php
echo $undefinedVar ?? "notice: undefined variable";
echo "\n";
echo 10 / 2; // no error
?>

Configuring Error Reporting Level

The error_reporting() function controls which of those severities actually get displayed or logged, letting you show everything during development while silencing minor notices in production.

Example: Configuring Error Reporting Level

php
<?php
error_reporting(E_ALL);
echo "All errors, warnings, and notices will now be shown";
?>

Triggering Custom Errors

trigger_error() lets your own code raise a warning or notice on demand, which is useful for flagging suspicious application-level conditions (like a deprecated function call) the same way PHP flags its own issues.

Example: Triggering Custom Errors

php
<?php
function useOldFunction() {
    trigger_error("This function is deprecated", E_USER_WARNING);
}
useOldFunction();
?>

Custom Error Handlers

set_error_handler() lets you register a custom function that intercepts PHP's built-in errors, so you can log them, format them consistently, or hide raw error details from end users.

Example: Custom Error Handlers

php
<?php
set_error_handler(function ($errno, $errstr) {
    echo "Custom handler caught: $errstr";
});
echo $undefinedVar;
?>

Clean Error Recovery

restore_error_handler() reverts back to PHP's default error handling once your custom handler is no longer needed, which matters if you only want custom handling active for a specific block of code.

Example: Clean Error Recovery

php
<?php
set_error_handler(function ($errno, $errstr) {
    echo "Custom: $errstr\n";
});
restore_error_handler();
echo "Back to PHP's default error handling";
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.