PHP
  Home arrow PHP arrow Page 4 - 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

Auto Loading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2007-12-04


    Table of Contents:
  • Auto Loading Classes in PHP 5
  • Traditional Approach
  • Traditional Approach continued
  • Using the Magic Function
  • Comparing the two

  • 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


    Auto Loading Classes in PHP 5 - Using the Magic Function
    ( Page 4 of 5 )


    Loading classes automatically: taking a first look at the “__autoload()” PHP 5 magic function

    As I explained in the previous section, PHP 5 comes equipped with the “__autoload()” magic function for automatically including all of the source classes required by a specific application into client code. In others words, the PHP 5 interpreter will simply invoke this function automatically when a determined script attempts to utilize a class that hadn’t been defined previously.

    This means that it’s possible to implement this function in such a way that it includes the source file of a given class when not available. Sounds rather confusing, doesn't it? Well, fear not. In order to clarify how the “__autoload()” function works, below I rewrote the script that you saw in the prior section, this time using the mentioned function.

    Please, have a close look at the following code sample:


    // include required classes using the magic '__autoload()' function

    function __autoload($className){

    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();

    }


    If you study in detail the above example, you’ll understand very easily how the  “__autoload()” PHP function does its business. As you can see, in this case the function in question will try to include two different files, called “mysql.php” and “result.php” respectively, whenever the pertinent definitions of the “MySQL” and “Result” classes are required by this sample database-driven application. In this way it implements a powerful mechanism for loading all the source classes demanded by a certain script.

    Of course, the major benefit of using this function is that’s no longer necessary to use a PHP include for each class that needs to be utilized. The “__autoload()” function will perform this task behind the scenes, so you won’t have to be concerned about this process. Pretty useful, right?

    Besides, it’s easy to see that all the scripts that work with this function will obviously need to implement it concretely. This can be a bit annoying, but I think that you’ll be more than happy using it within your PHP 5-based applications.

    Now that you've hopefully grasped the logic in utilizing the “__autoload()” PHP 5 magic function, it's time to read the last section of this tutorial, where I’ll be listing the complete definitions of the two practical examples that I developed earlier. You can evaluate adequately the pros and cons in loading source classes with conventional includes and with the “__autoload()” function.

    Go ahead and read the next few lines. I’ll be there, waiting for you.



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