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

描述:

公司项目PHP用作中间转发层(接收http请求,用 socket跟c++做通信),由于代码没有用到框架,这些东西自然就是之前的人自己写的。最近需要对这个底层进行优化,于是便看了下这部分的代码

目的:

这块代码的主要作用是把主目录下的所有插件类一次性全部加载进来。当使用尚未被定义的类(class)和接口(interface)时自动去加载。通过注册自动加载器,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

实现方法

主要用到PHP函数__autoload()

详细:

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

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...