Home >Backend Development >PHP Tutorial >Automatic Control Principles Lesson Answers Section 12 - Automatic Loading of Classes

Automatic Control Principles Lesson Answers Section 12 - Automatic Loading of Classes

WBOY
WBOYOriginal
2016-07-29 08:34:591209browse

/*
+------------------------------------------------ ----------------------------------+
| = This article is read by Haohappy<> ;
| = Notes from the Chapter Classes and Objects
| = Translation + personal experience
| = To avoid unnecessary trouble that may occur, please do not reprint, thank you
| = Criticisms and corrections are welcome, and I hope that all PHP enthusiasts Make progress together!
+-------------------------------------------------- ----------------------------------+
*/
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, which can be included in a file. After all, you know which class to use. However, PHP provides automatic Load function, which can save programming time. When you try to use a class that PHP has not organized into, it will look for a global function __autoload. If this function exists, PHP will call it with a parameter, which is the class's Name.
Example 6.15 illustrates how __autoload is used. It assumes that each file in the current directory corresponds to a class. When the script attempts to generate an instance of class User, PHP will execute __autoload. The script assumes that class_User.php defines There is a User class. Regardless of whether it is uppercase or lowercase when called, PHP will return the lowercase name.
Listing 6.15 Class autoloading

Copy code The code is as follows:

//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();
?>

The above has introduced the answers to the Principles of Automatic Control course. Section 12 - Automatic loading of classes, including the answers to the Principles of Automatic Control course. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn