Section 12 - Automatic loading of classes
When you try to use an undefined class, PHP will report a fatal error. The solution is to add a class, you can use include Include a file. After all, you know which class to use. However, PHP provides the autoloading function of classes, which can save programming time. When you try to use a class that PHP has not organized, it will look for an __autoload Global function. If this function exists, PHP will call it with one parameter, which is the name of the class.
Example 6.15 illustrates how __autoload is used. It assumes that there is one for each file in the current directory Class. When the script attempts to generate an instance of class User, PHP will execute __autoload. The script assumes that the User class is defined in class_User.php. Regardless of whether the call is in uppercase or lowercase, PHP will return the lowercase 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(); ?>