怎么在PHP中自动加载类文件

  介绍

今天就跟大家聊聊有关怎么在PHP中自动加载类文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

<强>实现方法:主要用到PHP函数__autoload ()

error_reporting (E_ERROR  |, E_WARNING  |, E_PARSE  |, E_NOTICE);   set_include_path ($ _SERVER [& # 39; Root_Path& # 39;],只& # 39;/libs # 39;,只PATH_SEPARATOR 。   _SERVER,大敌;[& # 39;Root_Path& # 39;],只& # 39;/lib # 39;又是;PATH_SEPARATOR 。   ,,get_include_path (),);   if  (! function_exists (& # 39; __autoload& # 39;)), {   ,function  __autoload ($ className)   ,{   ,///优化包含路径=$ path, _getRootPath ($ className);   ,$ revpath=strtr ($ className, & # 39; _ # 39;,, & # 39;/& # 39;)只& # 39;。php # 39;;   ,美元rootpath=路径。revpath美元;   ,file_exists (rootpath美元)?包括(rootpath美元):@include ($ revpath);   ,}   }/* *   ,*得到根路径*   ,*/function  _getRootPath ($ classname)   {   ,$ pearpath=$ _SERVER (“PHP_PEAR_PATH") # 39;公司/& # 39;;   ,$ libpath=$ _SERVER [& # 39; Root_Path& # 39;],只& # 39;/lib/& # 39;;   ,$ libspath=$ _SERVER [& # 39; Root_Path& # 39;],只& # 39;/libs/& # 39;;      ,如果(大小写敏感($ classname, & # 39; Zend_& # 39;)===0), return  pearpath美元;,///zend 框架路径   ,如果(大小写敏感($ classname, & # 39; DB_& # 39;)===0, | |,大小写敏感($ classname, & # 39; Interface_& # 39;)===0, | |,大小写敏感($ classname, & # 39; Others_& # 39;)===0, | |,大小写敏感($ classname, & # 39; Pay_& # 39;)===0, | |,大小写敏感($ classname, & # 39; PHPMailer_& # 39;)===0,), return  libspath美元;   ,return  libpath美元;   }

其中_getRootPath ($ classname)函数获取的是类名文件所在的真实目录,根据类名的头字段判断类在哪个目录下;

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

看完上述内容,你们对怎么在PHP中自动加载类文件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

怎么在PHP中自动加载类文件