When designing object-oriented program development, a PHP source file is usually created separately for each class definition. PHP will report a fatal error when you try to use a class that is not defined. You can use include or require to include the source file where a class is located, after all you know the class to use. If a page needs to use more than one class, you have to write a long list of included files at the beginning of the script page, including all the classes you need on this page. This processing is not only cumbersome, but also error-prone.
PHP provides automatic loading of classes, which saves you time in programming. When you try to use a class that is not organized by PHP, it looks for a autoload () global function (not a function declared in the class). If this function is present, PHP invokes it with a parameter, which is the name of the class.
The following example illustrates how AutoLoad () is used, assuming that each file in the current directory corresponds to a class, and that PHP automatically executes the autoload () function when the script attempts to create an instance of a class user. The script assumes that the user class is defined in user.class.php, and PHP returns the lowercase of the name, regardless of whether it is called in uppercase or lowercase. Therefore, in the project, when the organization defines the name of the class, you need to follow certain rules, must be the name of the class center, you can also add a unified prefix or suffix to form the file name, such as classname.class.php, xxx_classname.php, classname_ xxx.php or classname.php, the recommended class file is named using the "classname.class.php" format.
<?php/* declares a magic method for an auto-load class AutoLoad () */function autoload ($className) { //using the include included class file in the method include (Strtolower ($className). ". class.php");} $obj = new User (); The user class does not exist, the autoload () function is called automatically, and the class name "User" is passed in as a parameter to $obj2 = new shop (); >