Blogger Information
Blog 36
fans 1
comment 0
visits 26407
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP类的自动加载器
早晨
Original
542 people have browsed it

实现自动加载,应该遵循如下约定:

  1. 一个文件只有一个类
  2. 类名和文件名必须一致
  3. 类的命名空间,必须映射到类文件所在的路径
    use 默认必须是”完全限定名称”,所以"\"全局空间标识符可以不写
    根据系统不同,实现目录分隔符的转换
    $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    require __DIR__ . DIRECTORY_SEPARATOR. $class.'.php';

结构目录

Index.php代码

  1. <?php
  2. namespace index;
  3. // 引入自动加载
  4. require 'auto.php';
  5. use inc\con1;
  6. use inc\con2;
  7. use inc\con3;
  8. echo con1::index() . '<hr>';
  9. echo con2::index() . '<hr>';
  10. echo con3::index() . '<hr>';

Auto.php代码

  1. <?php
  2. // 自动加载
  3. spl_autoload_register(function ($class) {
  4. $dir = str_replace('\\', DIRECTORY_SEPARATOR, $class);
  5. require __DIR__ . DIRECTORY_SEPARATOR . $dir . '.php';
  6. });

Inc/con1.php代码

  1. <?php
  2. namespace inc;
  3. class con1
  4. {
  5. public static function index()
  6. {
  7. return __CLASS__ . '类<br>' . __METHOD__ . '方法';
  8. }
  9. }

Inc/con2.php代码

  1. <?php
  2. namespace inc;
  3. class con2
  4. {
  5. public static function index()
  6. {
  7. return __CLASS__ . '类<br>' . __METHOD__ . '方法';
  8. }
  9. }

Inc/con3.php代码

  1. <?php
  2. namespace inc;
  3. class con3
  4. {
  5. public static function index()
  6. {
  7. return __CLASS__ . '类<br>' . __METHOD__ . '方法';
  8. }
  9. }

加载运行效果

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!