Home  >  Article  >  Backend Development  >  Section 12 - Automatic loading of classes_PHP tutorial

Section 12 - Automatic loading of classes_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 16:01:12711browse

/*
+-------------------------------------------------- ----------------------------------+
| = This article is read by Haohappy<>
| = Notes from the Chapter Classes and Objects
| = Translation + personal experience
| = To avoid possible unnecessary trouble, please do not reprint, thank you
| = We welcome criticisms and corrections, and hope to make progress together with all PHP enthusiasts!
+-------------------------------- --------------------------------------------------+
*/

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 to include a file. After all, you know which class you want to use. However, PHP provides the automatic loading function of classes, which can save programming time. When you try to use a class that PHP has not organized, it will Looks for a global function __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 the current directory Each file corresponds to a 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 uppercase or lowercase, 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();
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/316932.htmlTechArticle/* +--------------------- -------------------------------------------------- --------+ |=This article is Haohappy's notes from the chapter ClassesandObjects when reading CorePHP Programming |=Translation is mainly + personal...
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