php – 来自不同文件和目录的自动加载类和函数

前端之家收集整理的这篇文章主要介绍了php – 来自不同文件和目录的自动加载类和函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个自动加载代码
  1. function __autoload($class_name)
  2. {
  3. //class directories
  4. $directorys = array(
  5. './Controls/','./Config/','./Utility/'
  6. );
  7. //for each directory
  8. foreach($directorys as $directory)
  9. {
  10. //see if the file exsists
  11. if(file_exists($directory.$class_name . '.PHP'))
  12. {
  13. require_once($directory.$class_name . '.PHP');
  14. //only require the class once,so quit after to save effort (if you got more,then name them something else
  15. return;
  16. }
  17. }
  18. }

我有三个目录,他们持有我所有的类和函数.

我可以在Controls目录中创建一个自动加载文件,并使用它来加载其他PHP文件中的所有函数或类,我的意思是例如/portal/main/index.PHP中的index.PHP文件

是否可以加载index.PHP文件中的控件和配置类,而不包括index.PHP文件上面的任何文件

我的意思是自动加载会自动了解哪个文件正在请求类或函数,并为其包含该文件.

更新的代码

  1. function __autoload($class_name)
  2. {
  3. //class directories
  4. $directorys = array(
  5. '/Controls/','/Config/','/Utility/'
  6. );
  7. //for each directory
  8.  
  9. $ds = "/"; //Directory Seperator
  10. $dir = dirname(__DIR__); //Get Current file path
  11. $windir = "\\"; //Windows Directory Seperator
  12. $path = str_replace($windir,$ds,$dir);
  13.  
  14. foreach($directorys as $directory)
  15. {
  16. //see if the file exsists
  17. if(file_exists( $path . $directory . $class_name . '.PHP'))
  18. {
  19. require_once( $path . $directory . $class_name . '.PHP');
  20. //only require the class once,then name them something else
  21. return;
  22. }
  23. }
  24. }

我已经更新了代码并且它包含了文件,但我唯一的问题是这个函数没有自动运行,

例如我的自动加载文件位于:root / Controls / autoload.PHP
我需要一些类和函数:root / portal / index.PHP

当我在index.PHP中定义类时,我得到文件不存在的错误
我应该手动调用index.PHP中的autoload.PHP文件

我如何使自动加载智能,我不应该包括在每个文件包括类?

请帮帮我.
提前致谢

简单的手动解决方案:将您的自动加载文件放在项目根目录中并将其包含在索引文件中,这将完成工作.

但如果你想使用htaccess或PHP.ini:
将名为.user.ini的文件放入文档根目录,并在其中添加auto_prepend_file指令:

  1. auto_prepend_file = /home/user/domain.com/init.PHP

文件必须位于PHP的include_path中.因此,您必须将文件的目录设置为PHP.ini中的include_path,或者使用PHP_value语句在.htaccess中执行.

  1. PHP_value include_path ".:/path/to/file_directory"
  2. PHP_value auto_prepend_file "file.PHP

如果在.htaccess中使用上述方法,请务必从PHP.ini中复制include_path并添加:/ path_to / file_directory,这样就不会丢失任何已经包含的内容.

或者,只需将:/ path / to / file_directory直接添加PHP.ini中的include_path即可

更新

如果无法修改include_path,则可以尝试指定auto_prepend_file的相对路径.这应该有效,因为发送的文件路径的处理方式与使用require()调用的方式完全相同:

  1. PHP_value auto_prepend_file "./file.PHP"

猜你在找的PHP相关文章