PHP AutoLoad Best Practices

Written by on November 13, 2008 in General - 12 Comments

Few days ago my friend Mark, added on my blog interesting comment regarding autoloading objects in PHP. While i think it is great to have quality comments like each of Mark’s comment, autoloading is a topic that requires a separate post.

What is autoloading? Every time you want to use a new class in your PHP project, first you need to include this class (using include or require language construct, that’s right this are not functions). However if you have __autoload function defined, inclusion will handle itself.

Basic Autoloading Example

Let’s look at the two examples below, both of them work exactly the same way. However, in first one we do not have autoload function defined, thus we need to include class definition manually, in second example new class is automatically loaded when it is first used.

include "classes/class.Foo.php";
 
$foo = new Foo;
$foo->start();
$foo->stop();

Now example, suggested by Mark.

function __autoload($class_name) 
{
    require_once $DOCUMENT_ROOT.“classes/class..$class_name..php”;
}
 
$foo = new Foo;
$foo->start();
$foo->stop();

How this works? Simple, if instance of Foo is created for the first time then __autoload is called nomen est omen automatically. As an argument is passed name of the class. This is simple yet effective use of this function, which allows for autoloading objects from certain directory.

Advanced Usage

The last, snippet was nice but what if we have lots of classes, or groups of classes that we want to keep together? This is the problem that Zend Framework developers had to face and they dealt with great.

function __autoload($class_name)
{
    $path = str_replace("_", "/", $class_name);
    require_once $path.".php";
}
 
$ffr = new Foo_File_Reader;
$ffw->doSomething();
 
$ffw = new Foo_File_Writer;
$ffw->doSomethingElse();

This is not the actual code from Zend Framework, but you can get the idea of how it works. All “_” signs are replaced with “/”, so when Foo_File_Reader is created for the first time __autoload functions tries to include /Foo/File/Reader.php, similarly, it looks Foo_File_Writer in /Foo/File/Writer.php . Of course classes inside this files should be named Foo_File_Reader and Foo_File_Writer not Reader and Writer as file names might suggest.

Additionaly it is a good practice to set include path (using set_include_path function) to allow using __autoload function as is.

Ok, this were to good solutions for using __autoload function, which one you use depend on the size of your project and how many objects will you need in your application, of course you are free to not use any of them and create your own method of auto loading objects.

About the Author

Greg Winiarski is a freelance PHP and JavaScript programmer. He specializes in web applications and WordPress development.

12 Comments on "PHP AutoLoad Best Practices"

  1. Mark November 14, 2008 at 5:59 pm ·

    Greg, that is good additional advice from you on __autoload(). I got this set_include_path() syntax to work for my previous example:

    set_include_path($DOCUMENT_ROOT. 'classes');

    or this related function also works:

    ini_set('include_path', $DOCUMENT_ROOT. 'classes');

    so then the __autoload function example can be simplified, if that is used first:

    function __autoload($class_name) {
      require_once("class.". $class_name. ".php");
    }

    Of course everyone codes their own way (they might not use the above “class.” file prefix, for example), but simpler is usually better in my opinion! :) Also hope this post formats ok. And thanks again for the helpful tutorials. We all have something new to learn.

    Mark

  2. Greg November 22, 2008 at 9:36 am ·

    Thanks for the comment Mark.

    That is sooo true, we should all learn something new every day (and then apply it, but this is completely different story :) )

  3. EastGhostCom December 23, 2009 at 6:42 pm ·

    IMPORTANT: Look into spl_autoload_register() which lets you manage a stack of several __autoload() functions.

  4. EastGhostCom December 23, 2009 at 6:47 pm ·

    Also, the require_once() is costly, VERY costly, even with APC. The guy who initially wrote this thought stream unfortunately (and erroneously) wrote require_once() instead of the far faster include(). Since PHP only calls __autoload() when it can not find in memory the class, there is absolutely zero (and in fact negative) sense in using require_once() when include() works just as well and is far faster to boot.

  5. BennieBoy April 19, 2010 at 3:30 pm ·

    With regards to using require_once() vs. include(); it really depends on how you want your script to handle the inclusion. Since require() and require_once() generate a “Fatal” error and end execution it may indeed the the most appropriate to prevent the display of further error messages or screen rendering if a class is not found.

    I definitely understand the lack in necessity for require_once() but it may still be good to use require() if the developer doesn’t want a script to continue if the class can’t be found.

  6. php autoloader April 21, 2010 at 10:24 pm ·

    There is an PHP autoloader implementation, which finds classes in any files dynamically:
    http://php-autoloader.malkusch.de/en/

    It uses an index and works perfectly with other autoloaders.

    @moderator: Remove the previous posting. I used the wrong URIs.

  7. Criss May 18, 2010 at 2:43 am ·

    The only problems that I have with __autoload and for that matter, with set_include_path too, is that they affect the entire script thread. If I’m writing an application that is to be included in other applications, this may generate serious conflicts with the parent application.

  8. Greg Winiarski May 18, 2010 at 5:40 pm ·

    @Criss i am using autoloading in WPJobBoard plugin and never had problem with it, sure it gives some overhead to the whole application but it can be done.

  9. design web london August 6, 2010 at 1:40 pm ·

    i want to achieve the functionality with jquery and php mysql just as similar to the twitter home page how can i load data from database and then populate it like twitter home page please help

  10. Duan January 17, 2011 at 9:47 am ·

    very nice, thanks for sharing

  11. Duan January 17, 2011 at 9:51 am ·

    hi buddy,can you show you msn?

  12. COBAY September 2, 2011 at 3:02 am ·

    Cool Best Practice.
    Thanks for your kind.

Leave a Comment