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.