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.
include "classes/class.Foo.php";
$foo = new Foo;
$foo->start();
$foo->stop();
Basic Autoloading Example
function __autoload($class_name)
{
require_once $DOCUMENT_ROOT.“classes/class.”.$class_name.“.php”;
}
$foo = new Foo;
$foo->start();
$foo->stop();
PHP Official
Other
Update
PHP 5 introduced the magic function __autoload() which is automatically called when your code references a class or interface that hasn’t been loaded yet.
The major drawback to the __autoload()
function is that you can only provide one autoloader with it. PHP 5.1.2 introduced spl_autoload()
which allows you to register multiple autoloader functions, and in the future the __autoload()
function will be deprecated.
The introduction of spl_autoload_register()
gave programmers the ability to create an autoload chain, a series of functions that can be called to try and load a class or interface. For example:
<?php
function autoloadModel($className) {
$filename = "models/" . $className . ".php";
if (is_readable($filename)) {
require $filename;
}
}
function autoloadController($className) {
$filename = "controllers/" . $className . ".php";
if (is_readable($filename)) {
require $filename;
}
}
spl_autoload_register("autoloadModel");
spl_autoload_register("autoloadController");