php基础,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();
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!