您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

详解PHP框架自动加载类的文件原理

2024/6/13 20:09:30发布28次查看
这篇文章主要为大家详细介绍了php框架自动加载类文件原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
描述:公司项目php用作中间转发层(接收http请求,用 socket跟c++做通信),由于代码没有用到框架,这些东西自然就是之前的人自己写的。最近需要对这个底层进行优化,于是便看了下这部分的代码。
目的:这块代码的主要作用是把主目录下的所有插件类一次性全部加载进来。当使用尚未被定义的类(class)和接口(interface)时自动去加载。通过注册自动加载器,脚本引擎在 php 出错失败前有了最后一个机会加载所需的类。
实现方法:主要用到php函数__autoload()
详细:
error_reporting(e_error | e_warning | e_parse | e_notice); set_include_path($_server['root_path'] . '/libs' . path_separator . $_server['root_path'] . '/lib' . path_separator . get_include_path() ); if (!function_exists('__autoload')) { function __autoload($classname) { ///优化包含路径 $path=_getrootpath($classname); $revpath=strtr($classname, '_', '/'). '.php'; $rootpath=$path.$revpath; file_exists($rootpath)?include($rootpath):@include($revpath); } } /** *得到根路径* */ function _getrootpath($classname) { $pearpath=$_server["php_pear_path"].'/'; $libpath=$_server['root_path'] . '/lib/'; $libspath=$_server['root_path'] . '/libs/'; if(strpos($classname,'zend_')===0) return $pearpath; ///zend 框架路径 if(strpos($classname,'db_')===0 || strpos($classname,'interface_')===0 || strpos($classname,'others_')===0 || strpos($classname,'pay_')===0 || strpos($classname,'phpmailer_')===0 ) return $libspath; return $libpath; }
其中_getrootpath($classname)函数获取的是类名文件所在的真实目录,根据类名的头字段判断类在哪个目录下;
如果类能在这些目录下找到,类在使用前就会被加载。
以上就是详解php框架自动加载类的文件原理的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product