PHP
  Home arrow PHP arrow Page 2 - Error Handling in PHP: Coding Defensively
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Error Handling in PHP: Coding Defensively
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 47
    2006-01-11


    Table of Contents:
  • Error Handling in PHP: Coding Defensively
  • Killing your scripts: basic error handling with the “die()” statement
  • Triggering errors: more efficient error handling with the “trigger_error()” function
  • The PEAR way: looking at the PEAR_Error object
  • True and false: handling errors with Boolean flags

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Error Handling in PHP: Coding Defensively - Killing your scripts: basic error handling with the “die()” statement
    ( Page 2 of 5 )

    The first example that implements the basics of script-level error handling is based on the popular “die()” statement. For this reason, I’ll write a simple PHP class, which reads contents from a data file. In its basic incarnation, this class looks like this:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        $this->file=$file;
      }
      function getContent(){
        return file_get_contents("{$this->fileDir}{$this->file}.php");
      }
    }

     

    As I mentioned earlier, the above class implements a trivial file reader. Aside from the constructor, the class exposes only one public method, “getContent()”, which reads the content from a file passed in as an argument to the constructor. As you can see, the class has been coded with no error checking lines, so any object instantiated from it will cause a non-fatal error if the “$file” parameter doesn’t point to a valid file. The lines below show this circumstance:

    // instantiate FileReader object
    // pass in invalid file to the constructor
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    Warning: file_get_contents(fileDir/.php): failed to open stream: No such file or directory in /path/to/file/exceptions.php on line 4.

    Although the example is rather crude, it demonstrates in a nutshell how a class written without any error handler can be easily broken up. Now, in order to implement a basic error handler, I’m going to include some “die()” statements within the class methods, as follows:

    class FileReader{
      var $file;
      var $fileDir='fileDir/';
      function FileReader($file){
        if(!file_exists("{$this->fileDir}{$file}.php")){
          die('File '.$file.' not found');
        }
        $this->file=$file;
      }
      function getContent(){
        if(!$content=file_get_contents("{$this->fileDir}{$this->file}.php")){
          die("Unable to read file contents");
        }
        return $content;
      }
    }

     

    Now, the class looks subtly better and more efficient. Notice how a couple of “die()” statements allow you to code defensively, and introduce an appreciable difference compared to the earlier version. In this case, if I instantiate a new “file reader” object, by pointing it to an inexistent file, this is what I should get as a result:

    // instantiate FileReader object
    $fr=new FileReader('inexistent_file');
    // echo file content
    echo $fr->getContent();

    File inexistent_file not found.

    As you can see, the above snippet is a little more efficient, because it implements a simple error handling mechanism. Instead of leaving out of control conflictive operations, such as reading file contents, the class is capable at least of stopping program execution if an error occurs. Indeed, this is a considerable improvement from a programming point of view, and certainly didn’t demand any hard work from us.

    However, pseudo functions like “die()” statements are rather inflexible. After all, it doesn't always happen that a script must be abruptly terminated. Fortunately, PHP exposes other functions which are more helpful and flexible for handling errors. Considering this, let’s move on and have a look at the PHP built-in “trigger_error()” function, in order to find out how it can be used.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek