SoFunction
Updated on 2025-04-08

Section 12 Automatic loading of classes [12]


When you try to use an undefined class, PHP will report a fatal error. The solution is to add a class, which can include a file. After all, you know which class to use. However, PHP provides the automatic loading function of the class, which can save programming time. When you try to use a class that PHP does not organize, it will look for a global function of __autoload. If this function exists, PHP will call it with a parameter, which is the name of the class.

Example 6.15 illustrates how __autoload is used. It assumes that each file in the current directory corresponds to a class. When the script tries to generate an instance of User, PHP will execute __autoload. The script assumes that there is a User class defined in class_User.php. Regardless of whether it is uppercase or lowercase when calling, PHP will return lowercase of the name.

Listing 6.15 Class autoloading
<?php
//define autoload function
function __autoload($class)
{
include("class_" . ucfirst($class) . ".php");
}

//use a class that must be autoloaded
$u = new User;
$u->name = "Leon";
$u->printName();
?>