PHP
  Home arrow PHP arrow Page 4 - The Standard PHP Library, Part 1
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

The Standard PHP Library, Part 1
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 40
    2004-12-07


    Table of Contents:
  • The Standard PHP Library, Part 1
  • Simple Example
  • The Exception Class Hierarchy
  • A Simple Exception Extension

  • 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


    The Standard PHP Library, Part 1 - A Simple Exception Extension
    ( Page 4 of 4 )

    The Standard PHP Library

    Using our example code above, we can demonstrate a simple extension of the Exception class.

    class DivisionByZeroException extends Exception{}

    class WrongParameterTypeException extends Exception{}

    class Math {
      function divide($divisor, $dividend = 1) {
        if (!is_numeric($divisor))
        throw(new WrongParameterTypeException('Divisor is not a number'));
        if (!is_numeric($dividend))
        throw(new WrongParameterTypeException('Dividend is not a number'));
        if ($dividend == 0)
        throw(new DivisionByZeroException('Division by zero'));
       
        return ($divisor / $dividend);
      }
    }

    try {
      print divide(1, 0);
    }
    catch(WrongParameterTypeException $e) {
      print $e;
    }
    catch(DivisionByZeroException $e) {
      print $e;
    }

    Using this approach, we are able to easily handle different errors in different ways, and this is where the real value of extending the Exception class comes in. We can chain an unlimited number of catch blocks together to capture the different types of exceptions that could have occurred. We could accomplish a similar feat using error codes (remember the second parameter to the Exception class constructor). To do this we would typically define class constants to identify the error type. We could ammend our code to look like this, for example.

    Class Math {
      const DIVISION_BY_ZERO = 1;
      const WRONG_PARAMETER_TYPE = 2;
     
      public static function divide($divisor, $dividend = 1) {
        if (!is_numeric($divisor))
        throw(new Exception('Divisor is not a number', self::WRONG_PARAMETER_TYPE));
        if (!is_numeric($dividend))
        throw(new Exception('Dividend is not a number', self::WRONG_PARAMETER_TYPE)); 
        if ($dividend == 0)
        throw(new Exception('Division by zero', self::DIVISION_BY_ZERO));
       
        return ($divisor / $dividend);
      }
    }

    try {
      print Math::divide(1, 0);
    }
    catch(Exception $e) {
      if ($e->getCode() == Math::WRONG_PARAMETER_TYPE))
        die('You passed divide() a non-numeric value');
      if ($e->getCode() == Math::DIVISION_BY_ZERO))
        die('You tried to divide by zero');
      print $e;
    }

    The same end result is achieved with a different approach. Ultimately this is a matter of taste, but in my experience I have found it easier to keep up with exception classes. Regardless of your individual taste in approaches, this method of error handling is far more elegant and intuitive than anything available in PHP up until now, so take advantage of it.

    Conclusion

    Exceptions serve two main purposes: to simplify debugging and to allow for graceful error handling. They alllow a clean structure for identifying and creating errors at the script level, and allow simplified error recovery. The PHP 5 implementation of exceptions is, for all intents and purposes, identical to exception handling in Java, .NET and other languages capable of exception handling. Proper use of exceptions in PHP applications should help shed blobs of ugly legacy error handling and clean up code in general considerably. It allows the elimination of a lot of bulky error checks and the consolidation of error handling and recovery routines. Exceptions should be practiced religiously in PHP 5 applications.

    Our next installment will discuss another important chunk of the SPL: Iterators. See you soon!



     
     
    >>> More PHP Articles          >>> More By David Fells
     

       

    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 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek