Bird
Raised Fist0
PHPprogramming~10 mins

Set_error_handler function in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Set_error_handler function
Start Program
↓
Call set_error_handler
↓
Error occurs?
No→Continue normal execution
Yes↓
Custom error handler called
↓
Handle error (log, display, etc.)
↓
Return control to program
↓
Program ends
The program sets a custom error handler, then when an error happens, it calls that handler to manage the error before continuing.
Execution Sample
PHP
<?php
function myErrorHandler($errno, $errstr) {
  echo "Error: [$errno] $errstr\n";
}
set_error_handler('myErrorHandler');
echo $undefinedVar;
?>
This code sets a custom error handler that prints error details, then triggers an error by using an undefined variable.
Execution Table
StepActionEvaluationResult
1Define function myErrorHandlerFunction createdReady to handle errors
2Call set_error_handler('myErrorHandler')Set custom error handlerErrors now use myErrorHandler
3Execute echo $undefinedVar;Undefined variable error triggeredCall myErrorHandler with error info
4Inside myErrorHandlerPrint error messageOutput: Error: [8] Undefined variable: undefinedVar
5Return from myErrorHandlerError handledProgram continues
6Program endsNo more codeExecution complete
💡 Program ends after handling the undefined variable error with custom handler
Variable Tracker
VariableStartAfter Step 3After Step 5Final
$errnoN/A8 (Notice)8 (Notice)8 (Notice)
$errstrN/A"Undefined variable: undefinedVar""Undefined variable: undefinedVar""Undefined variable: undefinedVar"
$undefinedVarUndefinedUndefined error triggeredUndefined error handledUndefined
Key Moments - 2 Insights
Why does the custom error handler get called when echoing an undefined variable?
Because echoing an undefined variable triggers a notice error, and set_error_handler directs PHP to call the custom handler instead of the default error behavior, as shown in step 3 and 4 of the execution_table.
Does the program stop after the error is handled?
No, after the custom error handler runs (step 4 and 5), the program continues normally until it ends, as shown in step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 4?
AError: [8] Undefined variable: undefinedVar
BFatal error: Undefined variable
CNo output
DWarning: Variable undefinedVar not set
💡 Hint
Check the 'Result' column at step 4 in the execution_table.
At which step does the custom error handler get set?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column to find when set_error_handler is called.
If the error handler function was not set, what would happen at step 3?
AThe program would ignore the error and continue silently
BPHP would use the default error handler and show a notice
CThe program would crash immediately
DThe error would be logged but not displayed
💡 Hint
Recall that without set_error_handler, PHP uses its default error handling for notices.
Concept Snapshot
set_error_handler(functionName)
- Registers a custom function to handle PHP errors
- When an error occurs, PHP calls this function instead of default
- Function receives error number and message
- Allows custom error display or logging
- Program continues after handler unless stopped
Full Transcript
This example shows how PHP's set_error_handler function works. First, a custom function named myErrorHandler is defined to print error details. Then, set_error_handler is called with this function's name, so PHP uses it for errors. When the code tries to echo an undefined variable, PHP triggers a notice error. Instead of default handling, PHP calls myErrorHandler with error info. The handler prints the error message. After handling, the program continues and ends normally. Variables like $errno and $errstr hold error details during handling. This lets programmers control error messages and behavior in their PHP scripts.

Practice

(1/5)
1. What is the main purpose of the set_error_handler function in PHP?
easy
A. To define a custom function to handle errors when they occur
B. To stop all errors from appearing
C. To automatically fix errors in the code
D. To log errors to a file without any custom handling

Solution

  1. Step 1: Understand what set_error_handler does

    This function lets you tell PHP to use your own function to handle errors instead of the default error messages.
  2. Step 2: Compare options with this understanding

    Only defining a custom function to handle errors when they occur correctly describes this behavior. Automatically fixing errors, stopping all errors from appearing, and logging errors to a file without any custom handling are all incorrect.
  3. Final Answer:

    To define a custom function to handle errors when they occur -> Option A
  4. Quick Check:

    Custom error handling = Define function with set_error_handler [OK]
Hint: Remember: set_error_handler sets your own error function [OK]
Common Mistakes:
  • Thinking it stops errors completely
  • Assuming it fixes errors automatically
  • Confusing it with error logging functions
2. Which of the following is the correct syntax to set a custom error handler function named myErrorHandler?
easy
A. set_error_handler(&myErrorHandler);
B. set_error_handler(myErrorHandler);
C. set_error_handler('myErrorHandler');
D. set_error_handler($myErrorHandler);

Solution

  1. Step 1: Recall the syntax for passing function names in PHP

    When passing a function name as a callback, it must be a string in quotes.
  2. Step 2: Check each option

    set_error_handler('myErrorHandler'); correctly passes the function name as a string. set_error_handler(myErrorHandler); misses quotes, set_error_handler(&myErrorHandler); uses an invalid reference operator, and set_error_handler($myErrorHandler); uses a variable which is incorrect here.
  3. Final Answer:

    set_error_handler('myErrorHandler'); -> Option C
  4. Quick Check:

    Function name as string = 'myErrorHandler' [OK]
Hint: Function names as strings in callbacks [OK]
Common Mistakes:
  • Omitting quotes around function name
  • Using variable instead of string
  • Using reference operator & incorrectly
3. What will be the output of the following PHP code?
function customError($errno, $errstr) {
    echo "Error: [$errno] $errstr";
}
set_error_handler('customError');
trigger_error('This is a test error', E_USER_WARNING);
medium
A. Warning: This is a test error
B. Error: [512] This is a test error
C. Fatal error: Uncaught Error
D. No output

Solution

  1. Step 1: Understand the custom error handler and trigger_error

    The customError function prints the error number and message. The trigger_error calls this handler with E_USER_WARNING which has error number 512.
  2. Step 2: Predict the output

    The output will be the echo from customError showing the error number and message exactly as coded.
  3. Final Answer:

    Error: [512] This is a test error -> Option B
  4. Quick Check:

    Custom handler prints error number 512 and message [OK]
Hint: E_USER_WARNING error number is 512 [OK]
Common Mistakes:
  • Expecting default PHP warning format
  • Confusing error numbers
  • Thinking no output appears
4. Identify the error in this PHP code snippet using set_error_handler:
function handler($errno, $errstr) {
    echo "Error: $errstr";
}
set_error_handler(handler);
trigger_error('Oops!');
medium
A. trigger_error requires two arguments
B. trigger_error cannot be used with set_error_handler
C. handler function must return a value
D. Missing quotes around handler in set_error_handler

Solution

  1. Step 1: Check the set_error_handler syntax

    The function name passed to set_error_handler must be a string, so it needs quotes.
  2. Step 2: Verify trigger_error usage

    trigger_error can be called with one argument; the second is optional. The handler function does not need to return a value. Using trigger_error with set_error_handler is valid.
  3. Final Answer:

    Missing quotes around handler in set_error_handler -> Option D
  4. Quick Check:

    Function name must be string in quotes [OK]
Hint: Function names need quotes in set_error_handler [OK]
Common Mistakes:
  • Omitting quotes around function name
  • Thinking trigger_error needs two arguments
  • Expecting handler to return a value
5. You want to log all warnings and notices to a file instead of displaying them. Which approach using set_error_handler is best?
hard
A. Create a function that writes error details to a log file and set it with set_error_handler
B. Use set_error_handler with an empty function to ignore errors
C. Call trigger_error inside set_error_handler to log errors
D. Disable error reporting and rely on PHP default logging

Solution

  1. Step 1: Understand the goal

    You want to capture warnings and notices and save them to a file instead of showing them on screen.
  2. Step 2: Evaluate options

    Create a function that writes error details to a log file and set it with set_error_handler correctly describes creating a custom function that writes error info to a log file and setting it as the error handler. Use set_error_handler with an empty function to ignore errors ignores errors, which is not logging. Call trigger_error inside set_error_handler to log errors misuses trigger_error inside the handler, causing recursion. Disable error reporting and rely on PHP default logging disables reporting but does not customize logging.
  3. Final Answer:

    Create a function that writes error details to a log file and set it with set_error_handler -> Option A
  4. Quick Check:

    Custom handler writes logs = best practice [OK]
Hint: Custom handler writes logs to file for error control [OK]
Common Mistakes:
  • Ignoring errors instead of logging
  • Calling trigger_error inside handler causing loops
  • Disabling errors without custom logging
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard