这里有新鲜出炉的 PHP 教程,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
这篇文章主要为大家详细介绍了 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) 函数获取的是类名文件所在的真实目录,根据类名的头字段判断类在哪个目录下;
如果类能在这些目录下找到,类在使用前就会被加载。
来源: http://www.phperz.com/article/17/0809/339614.html