Specifications
Triggering Your Own Errors
The function trigger_error()can be used to trigger your own errors. Errors created in this
way will be handled in the same way as regular PHP errors.
The function requires an error message, and can optionally be given an error type. The error
type needs to be one of E_USER_ERROR, E_USER_WARNING, or E_USER_NOTICE. If you do not
specify a type, the default is E_USER_NOTICE.
You use
trigger_error() as shown in the following:
trigger_error(“This computer will self destruct in 15 seconds”,
E_USER_WARNING);
(Note that this function was added at PHP version 4.0.1.)
Handling Errors Gracefully
If you come from a C++ or Java background, you might miss exception handling when you use
PHP. Exceptions allow functions to signal that an error has occurred and leave dealing with the
error to an exception handler. Although PHP does not have exceptions, PHP 4.0.1 introduced a
mechanism that can be used in a similar way.
You have already seen that you can trigger your own errors. You can also provide your own
error handlers to catch errors.
The function set_error_handler() lets you provide a function to be called when user level
errors, warnings, and notices occur. You call set_error_handler() with the name of the func-
tion you want to use as your error handler.
Your error handling function must take two parameters; an error type and an error message.
Based on these two variables, your function can decide how to handle the error. The error type
must be one of the defined error type constants. The error message is a descriptive string.
A call to set_error_handler() will look like this:
set_error_handler(“myErrorHandler”);
Having told PHP to use a function called myErrorHandler(), we must then provide a function
with that name. This function must have the following prototype:
myErrorHandler(int error_type, string error_msg)
but what it actually does is up to you.
Building Practical PHP and MySQL Projects
P
ART V
492
29 7842 CH23 3/6/01 3:41 PM Page 492










