PHP自动加载机制,Autoloader、spl_autoload_register

EN
EN
2022-06-24 / 0 评论 / 193 阅读 / 正在检测是否收录...

php自动加载DEMO
l4rw81ns.png

创建autoloader.php文件

<?php

/**
 *
 * 自动载入函数
 */
class Autoloader
{
    /**
     * 向PHP注册在自动载入函数
     */
    public static function register()
    {
        spl_autoload_register(array(new self, 'autoload'));
    }

    /**
     * 根据类名载入所在文件
     */
    public static function autoload($className)
    {
        echo "自动加载-文件名--".$className."<br>";
        // DIRECTORY_SEPARATOR:目录分隔符,linux上就是’/’    windows上是’\’
        $filePath = __DIR__ . DIRECTORY_SEPARATOR . $className;
        $filePath = str_replace('\\', DIRECTORY_SEPARATOR, $filePath) . '.php';
        echo "自动加载-文件路径--".$filePath."<br>";
        if (file_exists($filePath)) {
            require_once $filePath;
        } else {
            echo "无法加载" . $filePath;
        }

    }
}

创建 test1.phptest2.php 文件

test1.php

<?php
include 'autoloader.php';
Autoloader::register();

echo  Dog::ww();

echo "<hr>";

echo  \lib\msg\Msg::json_en(['code'=>1,'msg'=>'哈哈哈哈']);

echo "<hr>";

$view = \lib\View::dispaly();

test2.php

<?php
include 'autoloader.php';
Autoloader::register();

use lib\msg\Msg;
use lib\View;

echo  Dog::ww();

echo "<hr>";


echo Msg::json_en(['code'=>1,'msg'=>'哈哈哈哈']);

echo "<hr>";

$view = View::dispaly();

Dog、View、Msg就是需要被自动加载的类文件,

l4rw957g.png
l4rw9cv6.png
l4rw9kis.png

0

评论

博主关闭了当前页面的评论