Home  >  Article  >  Backend Development  >  第十二节类的自动加载[12]_PHP

第十二节类的自动加载[12]_PHP

WBOY
WBOYOriginal
2016-06-01 12:38:19612browse

当你尝试使用一个未定义的类时,PHP会报告一个致命错误. 解决方法就是添加一个类,可以用include包含一个文件. 毕竟你知道要用到哪个类. 但是,PHP提供了类的自动加载功能, 这可以节省编程的时间. 当你尝试使用一个PHP没有组织到的类, 它会寻找一个__autoload的全局函数. 如果存在这个函数,PHP会用一个参数来调用它,参数即类的名称.

例子6.15说明了__autoload是如何使用的. 它假设当前目录下每个文件对应一个类. 当脚本尝试来产生一个类User的实例,PHP会执行__autoload. 脚本假设class_User.php中定义有User类.. 不管调用时是大写还是小写,PHP将返回名称的小写.

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