Automatic loading of classes in php

无忌哥哥
Release: 2023-04-01 20:56:02
Original
2302 people have browsed it

* 类的自动加载

 * 1.如果要在当前脚本中使用很多对象时,就不得不在头部使用require或include加载很多的类文件

 * 2.为了避免这种情况,推荐使用类的自动加载器,用户在创建对象时,就不必关心当前类是否已导入

 * 3.类的自动加载,使用了标准php函数库中的spl_autoload_register()函数来实现

 * 4.sql_autoload_register(类名),多个类名请放在数组中

//require './class/Demo1.php';

//require './class/Demo2.php';

//以上只是二个类文件的导入,如果是20个,甚至上百个类文件导入,将会非常麻烦

//使用类自动加载器,将会极大的简化以上操作

spl_autoload_register(function($className){
//    require './class/'.Demo1.'.php';
//    require './class/'.$className.'.php';
//    存在命名空间时,应该先将命名空间中的反斜线进行转义后,变成目录后再处理
//      $className = str_replace("\\", "/", $className);
      $path = __DIR__.'/class/'.$className.'.php';
      if (is_file($path) && file_exists($path)) {
          require $path;
      }
    
});
echo Demo1::CLASS_NAME;
echo &#39;<hr>&#39;;
echo Demo2::CLASS_NAME;
Copy after login

The above is the detailed content of Automatic loading of classes in php. 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