How to use PHP's __autoload function

Posted in PHP -

PHP introduced the __autoload() function in version 5 which is called whenever the code tries to use a class that has not yet been defined. You simply put some code into __autoload() to include the appropriate class file and don't have to bother about manually including those files. This post looks at how to do this with examples.

Update June 15th 2009: Be sure to also read my "Autoloading with PHP's SPL library" post which covers a way of allowing multiple autoloading functions with PHP. Update ends.

A simple example of using PHP's __autoload function is like so:

function __autoload($classname) {
    include("classes/$classname.class.php");   
}

If you then ran the following code

$foo = new foo;

and the "foo" class had not yet been defined, __autoload is called passing "foo" as the parameter. The example __autoload function then includes the appropriate file which as defined in the above example would be "classes/foo.class.php", although you would change this to whatever your naming convention and location of class files is.

Note that there's no need to use include_once() or require_once() to include the files - just include() or require() will do. This is because __autoload won't need to be called again if you create another instance of the class because the class is already defined. The following illustrates this:

echo "new foo<br />";
$foo = new foo;
echo "new foo<br />";
$foo = new foo;
echo "new bar<br />";
$bar = new bar;

function __autoload($classname) {
    echo "autoload $classname<br />";
    include("classes/$classname.class.php");
}

The output from the above would be:

new foo
autoload foo
new foo
new bar
autoload bar

This shows that __autoload() was only called each time a class that wasn't already defined was used. Because the "foo" class had aready been defined the second time we create a foo object the class was already defined and did not need to be loaded again.

Using the autoload function in PHP is really useful because you don't need to bother including all the necessary class files at the start of each script: they will be automatically loaded as and when required.



Related posts:


Comments