HomePHP Page 5 - Error Handling in PHP: Coding Defensively
True and false: handling errors with Boolean flags - PHP
As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.
The last error handling method we'll review here is perhaps the most ancient. Boolean flags have been used from the very beginning of many programming languages, and PHP isn’t an exception. While they’re quite easy to implement, the major drawback is that they’re not very informative about the error that occurred and its context. Here’s a crude (and rather inefficient) implementation of the “FileReader” class, which uses Boolean flags:
class FileReader{ var $file; var $fileDir='fileDir/'; function FileReader($file){ if(!@file_exists("{$this->fileDir}{$file}.php")){ return false; } $this->file=$file; } function getContent(){ if(!@$content=file_get_contents("{$this->fileDir}{$this->file}.php")){ return false; } return $content; } }
Considering the definition for the above example, class errors might be handled as follows:
In the example, I’ve deliberately used the “@” error suppression operator, in order to avoid the complaints of the PHP interpreter and return a false value (or 0 or –1) when a failure happens. At first glance, you can see the inefficiency of this method, as well as its limited flexibility. However, this approach has proven to be quite successful in procedural applications, or when client code is capable of handling simple errors without overly polluting the whole application.
At this point, I’ve explored the pros and cons of common error handling approaches in PHP 4. Probably you’ll want to add a few more methods to my generic list, but in general terms, this is what you’ll need to use in most cases. Definitely, in large web applications, a set of error manipulating classes is preferred, so you can handle errors through a centralized point. However, the “trigger_error()/set_error_handler()” combination may suit the needs of small projects, so it’s worth considering.
To wrap up
In this first tutorial, I’ve hopefully covered the most common techniques for handling failures within PHP 4 applications. Over the second (and last part) of this series, I’ll be focusing attention on exceptions in PHP 5. As you’ll see, exceptions provide a powerful mechanism for handling errors through a centralized point, and offer a nice level of information on raised errors and their context. Want to know more? You’ll have to wait for the last part!