Prev | Current Page 293 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

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.
When My_Exception is instantiated with a language and an error code, it will read
in the appropriate language file, parsing each line into an associative array consisting
226 CHAPTER 8 ?–  ERRO R AND EXCEPTION HANDL ING
of the error code and its corresponding message. The My_Exception class 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];
}
} # end My_Exception
try {
throw new My_Exception("english",4);
}
catch (My_Exception $e) {
echo $e->getMessageMap();
}
Catching Multiple Exceptions
Good programmers must always ensure that all possible scenarios are taken into
account.


Pages:
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305