
批改狀態(tài):合格
老師批語:
關(guān)鍵字 spl_autoload_register(function ($class) {}
Demo1.php
namespace admin\controller;
class Demo1
{
public static function index()
{
return '這是Demo1下面的index方法,其路徑時: '.__METHOD__;
}
}
Demo2.php
namespace admin\controller;
class Demo2
{
public static function index()
{
return '這是Demo2下面的index方法,其路徑時: '.__METHOD__;
}
}
autoloader.php
自動加載器
作用:簡化了在引用多個類時需要一個一個使用require
引入當(dāng)前文件的重復(fù)操作
<?php
// 自動加載器
spl_autoload_register(function ($class) {
// 適配不同系統(tǒng)環(huán)境的路徑
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
// __DIR__ : 當(dāng)前文件的目錄
// DIRECTORY_SEPARATOR: 當(dāng)前系統(tǒng)路徑的分隔符‘\’或者‘/’
// 自動加載絕對路徑
require __DIR__ . DIRECTORY_SEPARATOR . $path . '.php';
});
index.php
中使用自動加載器,并調(diào)用Demo1.php
和Demo2.php
中的index
方法
// 引入自動加載器
require 'autoloader.php';
// 起別名
use admin\controller\Demo1;
use admin\controller\Demo2;
// 調(diào)用
echo Demo1::index(). '<br>';
echo Demo2::index(). '<br>';
使用自動加載器的前提:
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號