/*
+ ------------------------------------------------------------------------------- +
| = Read this article for Haohappy <Core PHP Programming>
| = Notes in the Classes and Objects chapter
| = Translation-oriented + personal experiences
| = Do not repost it to avoid unnecessary troubles. Thank you.
| = Thank you for your criticism and hope to make progress together with all PHP fans!
+ ------------------------------------------------------------------------------- +
*/
Section 12th -- 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 and include a file. after all, you know which class to use. however, PHP provides the automatic class loading function, which can save programming time. when you try to use a class that is not organized by PHP, it will look for a global function of _ autoload. if this function exists, PHP will use a parameter to call it. The parameter 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 a User-like instance, PHP will execute _ autoload. the script assumes that class_User.php defines the User class .. PHP returns the lower-case name no matter whether it is in upper or lower case.
Listing 6.15 Class autoloading
Copy codeThe Code is as follows: <? 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 ();
?>