Define an __autoload() function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
function __autoload($class_name) {
include $class_name . ‘.php’;
}
$obj = new MyClass1();
$obj2 = new MyClass2();
$obj3 = new MyClass3();
$obj4 = new MyClass4();
$obj5 = new MyClass5();
spl_autoload_register() provides a more flexible alternative for autoloading classes.
It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.
function my_autoloader($class) {
include ‘classes/’ . $class . ‘.class.php’;
}
spl_autoload_register(‘my_autoloader’);
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
include ‘classes/’ . $class . ‘.class.php’;
});
$obj = new MyClass1();
$obj2 = new MyClass2();
$obj3 = new MyClass3();
$obj4 = new MyClass4();
$obj5 = new MyClass5();