php spl_autoload_register用法

使用 spl_autoload_register 以函数回调的方式实现自动加载

实例

/index.php

<?php

//自动加载方法
function set_autoload_function($class)
{
    $class = explode('\\', trim($class));
    $class = end($class);

    //file = ./lib/Student.php
    $file = './lib/' . $class . '.php';
    if (file_exists($file)) include $file;

}

//注册自动加载类
spl_autoload_register( 'set_autoload_function');


$student = new Huyongjian\Lib\Student();
$student->show();

/lib/Student.php

<?php
namespace Huyongjian\Lib;

class Student
{
    public function show(){
        echo 'Huyongjian/Lib Student show';
    }
}

访问index.php 结果显示

Huyongjian/Lib Student show