PHP
  Home arrow PHP arrow Page 3 - Using the _autoload() Magic Function to Build Loader Appps in PHP
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

Using the _autoload() Magic Function to Build Loader Appps in PHP
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2009-06-24


    Table of Contents:
  • Using the _autoload() Magic Function to Build Loader Appps in PHP
  • Review: building a file loader class the old way
  • Loading files with the autoload PHP magic function
  • Implementing an enhanced exception mechanism

  • 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


    Using the _autoload() Magic Function to Build Loader Appps in PHP - Loading files with the autoload PHP magic function
    ( Page 3 of 4 )

      

    Undeniably, one of the most useful features incorporated into PHP 5, aside from its solid object model, is the set of magic functions, which permit you to automatically load a determined file. 

    As you may guess, in this particular case I’m talking about the “__autoload()” function. When this function is implemented, it allows you to build file loading scripts very quickly. 

    To demonstrate a simple usage of this function, I’m going to define a sample class called “User,” which will store some data about a specific user: their first and last names, and their email address. 

    Then, with that class available for testing purposes, I’m going to show how to include it in a script by directly using the “require_once()” function, and finally by means of the “__autoload()” function. 

    That being explained, here’s how the “User” class looks:

     

    class User

    {

    private $name = 'Alejandro';

    private $email = 'Gervasio';

     

    // constructor

    public function __construct($name = '', $email = '')

    {

    if ($name != '')

    {

    $this->name = $name;

    }

     

    if ($email != '')

    {

    $this->email = $email;

     

    }

    }

     

    // get user name

    public function get_name()

    {

    return $this->name;

    }

     

    // get user's email address

    public function get_email()

    {

    return $this->email;

    }

     

    function __toString()

    {

    return 'Name: ' . $this->name . ' Email: ' . $this->email;

    }

    }

     

    So far, nothing spectacular is going on here, right? As you can see, the above “User” class has some simple setter and getter methods that permit you to set and retrieve the first and last names of a given user, as well as their email address. 

    In addition, the “__toString()” magic method allows you to display the value of these properties very easily, but the rest of the class code is extremely easy to follow. 

    So far, so good. Now that the previous “User” class has been properly defined, say that you need to use it within a simple program. In a typical case, to do this you’d use a script similar to the one below:

     

    // loading the user class using require_once()

    require_once 'user.php';

    // create instance of User class

    $user = new User();

    // display user data

    echo $user;

     

    Again, this example doesn’t bear any further discussion, because of its simplicity. However, see what happens when the “User” class is included via the “__autoload()” function:

     

    // loading the user class using the __autoload() function

    function __autoload($class)

    {

    $file = $class . '.php';

    if (file_exists($file))

    {

    require_once($file);

    }

    }

    // create instance of User class

    $user = new User();

    // display user data

    echo $user;

     

    Definitely, things have become much more interesting at this point. The class has now been included in the previous script by implementing the “__autoload()” function in a pretty basic way. Though small, this is certainly an improvement that leads toward loading files automatically.  

    What’s more, it’s possible to make the “__autoload()” function throw an exception if the targeted file can’t be found. This feature has been implemented by the following script. Take a look at it, please:

     

    // example on loading a class using the __autoload() function triggering an exception

     

    // define a generic exception handler function

    function exception_handler($e)

    {

    echo $e->getMessage();

    }

     

    set_exception_handler('exception_handler');

     

    function __autoload($class)

    {

    $file = $class . '.php';

    if(!file_exists($file)){

    eval("class $class {}");

    throw new Exception('Class ' . $class . ' not found.');

    }

    require_once($file);

    }

     

    // create instance of User class

    $user = new User();

    // display user data

    echo $user;

     

    Well, admittedly the “eval()” function called when autoloading the “User” class isn’t the most elegant solution for triggering an exception, but it does a decent job when it comes to tying an error mechanism to the “__autoload()” function. 

    However, it’s possible to polish the definition of this function a bit more by creating a more efficient exception handling script. Therefore, I’m going to finish this article by showing you how to develop such a script in a few easy steps. 

    Now, please click on the link shown below and read the section to come.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Adding Ordering and Grouping Clauses to the ...
    - 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...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek