In this conclusion to a five-part article series on error and exception handling in PHP, you'll learn how to extend the exception class, and how to catch multiple exceptions. This article is exceprted from chapter eight of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
Extending the Exception Class
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.
WhenMyExceptionis instantiated with a language and 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. TheMyExceptionclass and a usage example are found in Listing 8-2.
Listing 8-2. The MyException Class in Action
class MyException 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]; } } # end MyException