php基础,php自动加载的实现代码示例

PHP技术
311
0
0
2022-04-14
标签   PHP基础

spl_autoload_register的使用

spl_autoload_register() 作为 __autoload() 的替代函数

使用示例

// 定义一个文件加载函数
function my_autoloader($class) {// exit($class);
    include 'classes/' . $class . '.class.php';
}

// 将文件加载函数注册到 spl_autoload_register() 中
spl_autoload_register('my_autoloader');

// 或者使用匿名函数将文件加载函数注册进spl_autoload_register() 中 
/*
spl_autoload_register(function ($class) {
    exit($class);
    include 'classes/' . $class . '.class.php';
});
*/

// 通过调用类来出发自动加载
new \APP\Demo();

完整代码示例

<?php

//定义当前的目录绝对路径
define('DIR', dirname(__FILE__));

class Loading { 
  public static function autoload($className){ 
  //根据PSR-O的第4点 把 \ 转换层(目录风格符) DIRECTORY_SEPARATOR ,//便于兼容Linux文件找。Windows 下(/ 和 \)是通用的//由于namspace 很规格,所以直接很快就能找到$fileName = str_replace('\\', DIRECTORY_SEPARATOR, DIR .'\\'. $className).'.php';

    if(is_file($fileName)){ 
      require $fileName; 
    }else{ 
      echo $fileName .' is not exist'; 
      die; 
    }
  }
}

//采用`命名空间`的方式注册。php 5.3 加入的
//也必须是得是static静态方法调用,然后就像加载namespace的方式调用,注意:不能使用use
spl_autoload_register("Loading::autoload");

//通过调用类则会自动触发自动加载
new \APP\Demo();