php自动加载
php自动载方法有两种.
第一种方案用__autoload,这个函数较简单,也较弱.
但有一问题没有解决, 就是在include前判断文件是否存在的问题.
?
1
2
3
4
5
6
7
8
9
10
11
12
|
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()
一个简单的例子
?
1
2
3
4
5
6
7
8
9
10
11
|
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');
// }
//}
spl_autoload_register();
$a = new Acls();
|
spl_autoload_register()会自动先调用spl_autoload()在路径中查找具有小写文件名的".php"程序.默认查找的扩展名还有".ini",还可以用spl_autoload_extenstions()注册扩展名.
在找不到的清况下,还可以通过自己定义函数查找
如
?
1
2
3
4
5
6
7
8
9
10
11
12
|
function loader1( $class )
{
//自己写一些加载的代码
}
function loader2( $class )
{
//当loader1()找不到时,我来找
}
spl_autoload_register( 'loader1' );
spl_autoload_register( 'loader2' );
|
还可以更多……..
MVC框架是如何实现自动加载的
首先设置路径
$include = array('application/controllers', 'application/models', 'application/library');
set_include_path(get_include_path() . PATH_SEPARATOR .implode(PATH_SEPARATOR, $config['include']));
在获取URL,解析出控制器与方法.
然后设置自动加载
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Loader
{
/**
* 自动加载类
* @param $class 类名
*/
public static function autoload( $class )
{
$path = '' ;
$path = str_replace ( '_' , '/' , $class ) . '.php' ;
include_once ( $path );
}
}
/**
* sql自动加载
*/
spl_autoload_register( array ( 'Loader' , 'autoload' ));
|
路由,实例化控制器,调用方法,你写的东西就开始执行了
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* 路由
*/
public function route()
{
if ( class_exists ( $this ->getController())) {
$rc = new ReflectionClass( $this ->getController());
if ( $rc ->hasMethod( $this ->getAction())) {
$controller = $rc ->newInstance();
$method = $rc ->getMethod( $this ->getAction());
$method ->invoke( $controller );
} else
throw new Exception( 'no action' );
} else
throw new Exception( 'no controller' );
}
|
初步的自动加载就完成了
到此这篇关于PHP实现自动加载机制的文章就介绍到这了,更多相关PHP自动加载内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!
原文链接:https://www.cnblogs.com/yuxing/archive/2010/06/19/1760742.html
相关文章
猜你喜欢
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 36
-
2025-06-04 72
-
2025-05-29 13
-
2025-06-04 79
-
2025-06-04 78
热门评论