PHP
  Home arrow PHP arrow Page 4 - Auto Loading Classes in PHP 5
Dev Shed Forums 
Administration  
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 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 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

Auto Loading Classes in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 10
    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:
      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

    PCmover - $15 Off with Coupon Code CJPH7Q

    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


       · Ever wanted to build PHP 5 scripts that load automatically your source classes...
       · Yeah I Used This For A While. But Notice That If You Have Some Variables Or...
       · Thank you for commenting on my PHP article. Yes, what you mention is a cons in using...
       · You did not say (or I missed it) what happens if you use both methodologies. If a...
       · Thank you for commenting on my PHP article. Concerning your question, simply I...
     

       

    PHP ARTICLES

    - Setting Up a Web-based Image Hosting Service
    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery
    - Using Timers to Benchmark PHP Applications
    - Benchmarking Applications with PHP
    - Setting Up a Web-Based File Manager: PHPfile...
    - Developing a Modular Class For a PHP File Up...
    - Setting Up a Web-Based File Manager: bfExplo...
    - Defining a Custom Function for File Uploader...
    - Parsing Child Nodes with the DOM XML extensi...
    - Creating an Error Handling Module for a PHP ...
    - Accessing Attributes and Cloning Nodes with ...
    - Retrieving Information on Selected Files wit...
    - Handling HTML Strings and Files with the DOM...
    - Building File Uploaders with PHP 5




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