05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

To turn off error reporting entirely, use:<br />

error_reporting(0);<br />

This ensures that, regardless of the errors encountered while processing and executing<br />

your script, no errors will be sent to the client (except parse errors, which cannot<br />

be suppressed). Of course, it doesn’t stop those errors from occurring. Better options<br />

for controlling which error messages are displayed in the client are shown in the section<br />

“Defining Error Handlers.”<br />

Triggering Errors<br />

You can throw an error from within a script with the trigger_error( ) function:<br />

trigger_error(message [, type]);<br />

The first parameter is the error message; the second, optional, parameter is the condition<br />

level, which is either E_USER_ERROR, E_USER_WARNING, or E_USER_NOTICE (the<br />

default).<br />

Triggering errors is useful when writing your own functions for checking the sanity<br />

of parameters. For example, here’s a function that divides one number by another<br />

and throws an error if the second parameter is zero:<br />

function divider($a, $b) {<br />

if($b == 0) {<br />

trigger_error('$b cannot be 0', E_USER_ERROR);<br />

}<br />

return($a / $b);<br />

}<br />

echo divider(200, 3);<br />

echo divider(10, 0);<br />

66.666666666667<br />

Fatal error: $b cannot be 0 in page.php on line 5<br />

Defining Error Handlers<br />

If you want better error control than just hiding any errors (and you usually do), you<br />

can supply <strong>PHP</strong> with an error handler. The error handler is called when a condition<br />

of any kind is encountered and can do anything you want it to, from logging to a file<br />

to pretty-printing the error message. The basic process is to create an error-handling<br />

function and register it with set_error_handler( ).<br />

The function you declare can take in either two or five parameters. The first two<br />

parameters are the error code and a string describing the error. The final three parameters,<br />

if your function accepts them, are the filename in which the error occurred, the<br />

line number at which the error occurred, and a copy of the active symbol table at the<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Error Handling | 305

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!