Section 12 Automatic loading of classes [12]_PHP Tutorial

WBOY
Release: 2016-07-21 16:10:21
Original
812 people have browsed it


PHP will report a fatal error when you try to use an undefined class. 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 loading of classes. 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 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 attempts to generate an instance of class User, PHP will execute __autoload. The script assumes class_User There is a User class defined in .php. Regardless of whether the call is in uppercase or lowercase, PHP will return the lowercase name.

Listing 6.15 Class autoloading
//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/314209.htmlTechArticleWhen 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 to use. But...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template