In this second part of a two-part series on error and exception handling in PHP, we focus specifically on handling exceptions. This article is excerpted from chapter 8 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Although PHP’s base exception class offers some nifty features, in some situations you’ll likely want to extend the class to allow for additional capabilities. For example, suppose you want to internationalize your application to allow for the translation of error messages. These messages reside in an array located in a separate text file. The extended exception class will read from this flat file, mapping the error code passed into the constructor to the appropriate message (which presumably has been localized to the appropriate language). A sample flat file follows:
1,Could not connect to the database! 2,Incorrect password. Please try again. 3,Username not found. 4,You do not possess adequate privileges to execute this command.
WhenMy_Exceptionis instantiated with a language and an error code, it will read in the appropriate language file, parsing each line into an associative array consisting of the error code and its corresponding message. TheMy_Exceptionclass and a usage example are found in Listing 8-2.
Listing 8-2. The My_Exception Class in Action
class My_Exception extends Exception {
function __construct($language,$errorcode) { $this->language = $language; $this->errorcode = $errorcode; }
function getMessageMap() { $errors = file("errors/".$this->language.".txt"); foreach($errors as $error) { list($key,$value) = explode(",",$error,2); $errorArray[$key] = $value; } return $errorArray[$this->errorcode]; }