PHP
  Home arrow PHP arrow Page 4 - Throwing Basic Exceptions When Auto Loading Classes in PHP 5
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

Throwing Basic Exceptions When Auto Loading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 6
    2007-12-11


    Table of Contents:
  • Throwing Basic Exceptions When Auto Loading Classes in PHP 5
  • Two examples of the _autoload() PHP 5 function
  • Triggering fatal errors with the _autoload() PHP 5 function
  • Developing a simple mechanism to throw exceptions

  • 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


    Throwing Basic Exceptions When Auto Loading Classes in PHP 5 - Developing a simple mechanism to throw exceptions
    ( Page 4 of 4 )

    In accordance with the concepts I deployed in the previous section, it’s perfectly feasible to implement a simple workaround that provides the handy “__autoload()” function with the ability to throw an exception when one source class can’t be loaded onto a given PHP 5 application.

    This rather tricky solution consists of creating the troubling class via an “eval()” command, and then explicitly throwing an exception. Logically this concept will be better grasped if you take a close look at the following example. Here it is:

    // include required classes (the magic '__autoload()' function now throws an exception when some of the required classes are not found)


    function __autoload($className){

    if(!file_exists($className.'.php')){

    eval("class $className {}");

    throw new Exception('Class not found');

    }

    require_once $className.'.php';

    }

    try{

    // connect to MySQL

    $db=new MySQL(array
    ('host'=>'host','user'=>'user','password'=>'password',
    'database'=>'database'));

    // fetch users from database table

    $result=$db->query('SELECT * FROM users ORDER BY id');

    // display user data

    while($row=$result->fetch()){

    echo 'Id: '.$row['id'].' First Name: '.$row['firstname'].' Last Name: '.$row
    ['lastname'].' Email: '.$row['email'].'<br />';

    }

    }

    catch(Exception $e){

    echo $e->getMessage();

    exit();

    }


    As shown above, the “__autoload()” magic function has been implemented by using the workaround that I mentioned before. As you can see, the function first check for the existence of the files that contain the corresponding source classes, and if this process fails for some reason, it tries to create the problematic class using the “eval()” function. Finally, the function throws an explicit exception, in this way implementing a basic error handling mechanism. Nothing too complex, right?

    Besides, if you first remove the pertinent “mysql.php” file and test the prior example on your own web server, you’ll get an error similar to the one shown below:

    Fatal error: Function __autoload(MySQL) threw an exception of type 'Exception' in path/to/file

    Indeed, this is an advance with reference to the raw fatal error that you saw earlier. As you can see, the “__autoload()” function now is capable of launching an exception, although it still won’t be caught by a “try-catch()” block.

    However, that’s all the code samples that I’m going to show you for the moment. I recommend that you test all of the examples developed in this tutorial to see how they react when a source class can’t be loaded as expected. It’s an instructive experience, trust me.

    Final thoughts

    In this second installment of the series you hopefully learned how to implement a simple workaround within the handy “__autoload()” magic function to incorporate into it the capacity to throw exceptions when a specific source class is not included. Nonetheless, this quick and dirty exception mechanism isn’t completely functional yet, since a conventional “try-catch()” block won’t be able to intercept these exceptions.

    However, this issue will be fixed in the next part of the series, so I hope to see you there!



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