PHP框架自动加载类文件原理详解
author:一佰互联 2019-04-25   click:193

描述:公司项目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)函数获取的是类名文件所在的真实目录,根据类名的头字段判断类在哪个目录下;

如果类能在这些目录下找到,类在使用前就会被加载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持网页设计。