PHP
  Home arrow PHP arrow Page 4 - Throwing Basic Exceptions When Auto Lo...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
Moblin 
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? 
PHP

Throwing Basic Exceptions When Auto Loading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Since the "__autoload()" PHP 5 magic function natively isn’t capable of throwing...
       · Although many subjects covered by the PHP section are interesting at first sight,...
       · This is an intro that should have been in the article, instead of all the blah blah...
       · What about the case where the class file exists, but the expected class is not found...
       · In first place I must thank you for the comments on my PHP article, and they’re...
       · Thanks for commenting here. Introductions are completely necessary, because that way...
       · Thank you Anders, for posting your question here. If the class file exists, but for...
       · Mate... I know everyone is bagging you out but I like your style of writing. Its...
       · Thank you for commenting on my PHP article. Hey, I’m glad to know you like my style...
     

       

    PHP ARTICLES

    - Handling Attachments in MIME Email with PHP
    - Completing the Project Management Application
    - Sending MIME Email with PHP
    - Handling Files for a Project Management Appl...
    - Viewing and Editing Tasks for a Project Mana...
    - More on Private Methods with PHP 5 Member Vi...
    - Adding Tasks to a Project Management Applica...
    - Utilizing Private Methods with PHP 5 and Mem...
    - Making Changes in a Project Management Appli...
    - Defining Public and Protected Methods with M...
    - HTML for a Project Management Application
    - Using Subclasses and Accessors with Member V...
    - Implementing Internet Protocols with PHP
    - Project Management: The Application
    - Working with Private Properties to Protect P...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway