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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【宜配屋www.yipeiwu.com】。

相关文章

关于php连接mssql:pdo odbc sql server

只有一个php_pdo_odbc.dll。 so~最新最好的php连接mssql方法应该是这样: 复制代码 代码如下: <?php $cnx = new PDO("odbc:Dri...

php三种实现多线程类似的方法

1、curl_multi方法 当需要多线程的时候,可以用curl_multi一次性请求多个操作来完成,但curl走的是网络通信,效率与可靠性就比较差了的。 function main...

php实现处理输入转义字符的代码

先来个函数,是最近WordPress 3.6中刚刚引入的 /** * Add slashes to a string or array of strings. * * This...

php flv视频时间获取函数

复制代码 代码如下:<?php   function BigEndian2Int($byte_word, $signed = false) {   $int_value = 0;...

PHP中::、-&amp;gt;、self、$this几种操作符的区别介绍

在访问PHP类中的成员变量或方法时,如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::,反之如果被引用的变量或者方法没有被声明成...