Home > Backend Development > PHP Tutorial > php自动加载的两种实现方法_PHP

php自动加载的两种实现方法_PHP

WBOY
Release: 2016-06-01 12:18:38
Original
881 people have browsed it

php自动载方法有两种.
第一种方案用__autoload,这个函数较简单,也较弱.
但有一问题没有解决, 就是在include前判断文件是否存在的问题.
复制代码 代码如下:
set_include_path('aa' . PATH_SEPARATOR . get_include_path());
function __autoload($className)
{
//如果加这个检测, 因为此文件不在当前目录下,它就会检测不到文件存在,
//但include是能成功的
if (file_exists($className . '.php')) {
  include_once($className . '.php');
} else {
exit('no file');
}
}
$a = new Acls();

第二种方案用spl自动加载,这里具体说一下这个.
spl_autoload_register()
一个简单的例子
复制代码 代码如下:
set_include_path('aa' . PATH_SEPARATOR . get_include_path());
//function __autoload($className)
//{
// if (file_exists($className . '.php')) {
// include_once($className . '.php');
// } else {
// exit('no file');
// }
/

Related labels:
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