In PHP 4 object-oriented scenarios, one of the most popular approaches for handling errors is the PEAR_Error object. While not all developers feel comfortable working with PEAR packages, admittedly it’s a very strong framework that can be used in numerous applications. Specifically, the PEAR_Error object is extremely useful for handling errors, and certainly provides a lot of information that you might need. Let’s have a look at its methods: - PEAR::getMessage(): returns the error message. Having described the corresponding object methods, the next step will consist of modifying the sample class, so it can return a PEAR_Error object, instead of using the “trigger_error()” function: // include PEAR library class FileReader{ As you can see, now the above class returns a PEAR_Error object when things go wrong. Given the existence of this object, I’m able to call one of its methods, as follows:
The above example demonstrates how to check for the existence of an error object, and accordingly call its “getMessage()” method. Evidently, this method provides much more flexibility and allows you to obtain specific information on both the nature of the error and the context in which it took place. Of course, this is only a introductory example, so if you feel curious about PEAR, visit its site (http://pear.php.net/) and browse the numerous packages available for downloading. Having scratched the surface of PEAR_Error objects, let’s leap forward and analyze the last method for handling program failures, in this case by utilizing Boolean flags.
blog comments powered by Disqus |