当前位置 博文首页 > fareast_mzh的博客:php autoload 自动加载

    fareast_mzh的博客:php autoload 自动加载

    作者:[db:作者] 时间:2021-08-13 15:58

    西部数码

    * autoload.php

    <?php
    /**
     * Created by PhpStorm.
     * User: EDZ
     * Date: 2020/6/22
     * Time: 11:01
     */
    
    $prefixList = [
        'DesignPatterns\\Structural\\Adaptor'
    ];
    
    foreach ($prefixList as $prefix) {
        // clazz "DesignPatterns\Structural\Adaptor\Book" remove ".php"
        // prefix "DesignPatterns\Structural\Adaptor"
        spl_autoload_register(function($clazz) use($prefix) {
            $len = strlen($prefix);
            if (0 != strncmp($prefix, $clazz, $len)) {
                return;
            }
            $baseDir = dirname(__FILE__) . DIRECTORY_SEPARATOR.
                str_replace('\\', DIRECTORY_SEPARATOR, $prefix);
            $relativeClass = substr($clazz, $len);
    
            $file = $baseDir.str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass).'.php';
            if (!file_exists($file)) {
                throw new \InvalidArgumentException($file.' does not exists');
            }
            require $file;
        });
    }

    需要注册的命名空间写到$prefixList列表中

    ?

    在index.php 入口文件中

    include "autoload.php";

    ?

    代码下载地址:

    https://download.csdn.net/download/fareast_mzh/12543444

    最新版 gitee

    https://gitee.com/mingzhanghui/PhpDesignPattern

    ?

    cs