Detailed explanation of the file principle of automatically loading classes in the PHP framework

怪我咯
Release: 2023-03-10 14:12:02
Original
1257 people have browsed it

This article mainly introduces the principle of automatic loading of class files by the PHP framework in detail, which has certain reference value. Interested friends can refer to it

Description: Company Project PHP is used as the intermediate forwarding layer (receiving http requests and using sockets to communicate with C++). Since the code does not use a framework, these things were naturally written by the previous people. Recently, I need to optimize this bottom layer, so I took a look at this part of the code.

Purpose: The main function of this code is to load all plug-in classes in the main directory at once. Automatically load classes and interfaces that have not yet been defined. By registering an autoloader, the scripting engine has a last chance to load the required classes before PHP fails with an error.

Implementation method: Mainly uses PHP function __autoload()

Details:

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;
}
Copy after login

The _getRootPath($classname) function obtains the real directory where the class name file is located, and determines which directory the class is in based on the header field of the class name;

If the class can be found in these directories , the class will be loaded before use.

The above is the detailed content of Detailed explanation of the file principle of automatically loading classes in the PHP framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template