1Example #1 Autoload example
2
3This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
4<?php
5spl_autoload_register(function ($class_name) {
6 include $class_name . '.php';
7});
8
9$obj = new MyClass1();
10$obj2 = new MyClass2();
11?>
12
13
1The introduction of spl_autoload_register() gave programmers
2the ability to create an autoload chain,
3a series of functions that can be called to try and load a class or interface.
4
5For example:
6
7<?php
8function autoloadModel($className) {
9 $filename = "models/" . $className . ".php";
10 if (is_readable($filename)) {
11 require $filename;
12 }
13}
14
15function autoloadController($className) {
16 $filename = "controllers/" . $className . ".php";
17 if (is_readable($filename)) {
18 require $filename;
19 }
20}
21
22spl_autoload_register("autoloadModel");
23spl_autoload_register("autoloadController");