How to handle errors using Boolean flags

This error handling method may be the most ancient. Boolean flags were used by many programming languages, and PHP will not be an exception. Even though they are very simple to apply, the main negative aspect is that they were not very informative about the mistake that happened and its perspective. Here is an unsophisticated implementation of the FileReader class, which make use of Boolean flags:

[php]
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;
}
}
[/php]

Bearing in mind about the explanation for the above example, class errors might be handled as follows:

[php]
$fr=new FileReader(‘inexistent_file’);
if(!$fr->getContent()){
die(‘Unable to read file contents’);
}
else{
echo $fr->getContent();
}
[/php]

In the example, @ error suppression operator is intentionally used, so as to stay away from the complaints of the PHP interpreter and return a false value (or 0 or -1) when a failure happens. At first look, you can observe the incompetence of this method, plus its restricted flexibility. On the other hand, this approach has established to be quite victorious in procedural applications, or when client code is able to handle straightforward errors without corrupting the entire application.

Nowadays, we have investigated the pros and cons of common error handling approaches in PHP 4. Certainly, in huge web applications, a set of error controlling classes is preferred, so you are able to handle errors through a centralized point. Conversely, the trigger_error () / set_error_handler () combination may suit the requirements of small projects, so it is worth considering.

No comments yet.

Leave a comment

Request a Free SEO Quote