1. 程式人生 > >php 自定義 autoload.php 自動載入類

php 自定義 autoload.php 自動載入類

* 目錄結構

* autoload.php

<?php
// autoload ./et/lib
spl_autoload_register(function($class) {
    $prefix = 'et\\lib';
    $base_dir = __DIR__ . DIRECTORY_SEPARATOR. str_replace('\\', '/', $prefix);
    // echo $base_dir.PHP_EOL;
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    // echo $file.PHP_EOL;
    if (file_exists($file)) {
        require $file;
    }
});

* ./et/lib/Debug.php

<?php
namespace et\lib;

class Debug {
    public static function dump($var){
        $trace_data = debug_backtrace();
        $debug_data = $trace_data[0];
        echo '*********Start************'. chr(10);
        $pos_info = $debug_data['file'] . ' on line:' . $debug_data['line'];
        echo $pos_info .  chr(10);
        echo var_export($var);
        echo  chr(10) . '*********End*************' . chr(10);
    }
}

* index.php

<?php
include "autoload.php";

use et\lib\Debug as Debug;

$a = [1,2,3];
Debug::dump($a);

E:\code\php\test\sms>php index.php *********Start************ E:\code\php\test\sms\index.php on line:7 array (   0 => 1,   1 => 2,   2 => 3, ) *********End*************