25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

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

34 ” <strong>PHP</strong> Basics<br />

i<br />

Error reporting can also be changed dynamically from within a script by calling the<br />

error_reporting() function.<br />

The display_errors and log_errors directives can be used to determine how errors<br />

are reported. If display_errors is turned on, errors are outputted to the script’s<br />

output; generally speaking, this is not desirable in a production environment, as everyone<br />

will be able to see your scripts’ errors. Under those circumstances, you will<br />

instead want to turn on log_errors, which causes errors to be written to your web<br />

server’s error log.<br />

Handling Errors<br />

Your scripts should always be able to recover from a trappable error—even if it’s<br />

just to advise the user that an error occurred and notify support staff of the same<br />

fact. This way, your script won’t simply capitulate when something unexpected<br />

occurs—resulting in better communication with your customers and the possible<br />

avoidance of some major problems.<br />

Luckily, error handling is very easy. Your scripts can declare a catch-all<br />

function that is called by <strong>PHP</strong> when an error condition occurs by calling the<br />

set_error_handler() function:<br />

$oldErrorHandler = ’’;<br />

function myErrorHandler ($errNo, $errStr, $errFile, $errLine, $errContext) {<br />

global $oldErrorHandler;<br />

logToFile("Error $errStr in $errFile at line $errLine");<br />

// Call the old error handler<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

if ($oldErrorHandler) {<br />

$oldErrorHandler ($errNo, $errStr, $errFile, $errLine, $errContext);<br />

}<br />

}<br />

$oldErrorHandler = set_error_handler (’myErrorHandler’);

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

Saved successfully!

Ooh no, something went wrong!