Autoloading
Autoloading loads a class file on demand when the class is first used. One registered rule replaces a separate load line for each class file.
A book loads on first use
The loader function turns a class name into a file name. Registering it by name lets the new Book line load the book file with no require line for the class.
<?php
function loadClass($class) {
require $class . ".php";
}
spl_autoload_register("loadClass");
$book = new Book("Dune");
echo $book->title . "\n";A second class loads the same way
The Reader class sits in its own file with the same naming rule. The same loader loads it when the class is first used.
<?php
function loadClass($class) {
require $class . ".php";
}
spl_autoload_register("loadClass");
$book = new Book("Dune");
$reader = new Reader("Ana");
echo $reader->reading($book) . "\n";A check proves the load is lazy
class_exists with false as its second value checks only and never loads. The first check runs before any Book is built, and the second check runs after.
<?php
function loadClass($class) {
require $class . ".php";
}
spl_autoload_register("loadClass");
var_dump(class_exists("Book", false));
$book = new Book("Dune");
var_dump(class_exists("Book", false));Example
<?php
function loadClass($class) {
require $class . ".php";
}
spl_autoload_register("loadClass");
$bookA = new Book("Dune");
$bookB = new Book("Emma");
$reader = new Reader("Ana");
echo $reader->reading($bookA) . "\n";
echo $reader->reading($bookB) . "\n";Key points
- spl_autoload_register registers a function as the class loader.
- PHP calls the loader with the class name when a program uses a class that is not loaded yet.
- The loader in this lesson turns the class name into a file name by adding the .php ending.
- A class that a program never uses never loads its file.
- class_exists checks whether a class is known.
In this example, one loader is registered by name. Two Book objects and one Reader object load their files on first use. The reader line prints once for each book.
Note
A closure can serve as the loader too, but a named function keeps the rule plain here.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does a registered autoloader run?