您可以将此文件包含在脚本的开头,然后只需设置目录级别而不是此常量:WP_CONTENT_DIR
这将自动包含它需要的任何文件
<?php
class autoload
{
private static function updatePhpFiles($dir_level, $php_files_json_name)
{
/**Get all files and directory using iterator.*/
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir_level));
$filePaths = array();
/**Get all php files in this directory level.*/
foreach ($iterator as $path) {
if (is_string(strval($path)) and pathinfo($path, PATHINFO_EXTENSION) == 'php') {
$filePaths[] = strval($path);
}
}
/**Encode and save php files dir in a local json file */
$fileOpen = fopen($dir_level . DIRECTORY_SEPARATOR . $php_files_json_name, 'w');
fwrite($fileOpen, json_encode($filePaths));
fclose($fileOpen);
}
private static function includeMatchingFiles($dir_level, $php_files_json_name, $class_file_name)
{
$files = json_decode(file_get_contents($dir_level . DIRECTORY_SEPARATOR . $php_files_json_name), true);
$inc_is_done = false;
/**Include matching files here.*/
foreach ($files as $path) {
if (stripos($path, $class_file_name)) {
require_once $path;
$inc_is_done = true;
}
}
return $inc_is_done;
}
public static function include_system_files($dir_level, $class_name)
{
$php_files_json = 'phpfiles.json';
$class_file_name = $class_name . '.php';
/**Include required php files.*/
if (is_file($dir_level . DIRECTORY_SEPARATOR . $php_files_json)) {
if (self::includeMatchingFiles($dir_level,$php_files_json, $class_file_name)) {
return true;
} else {
self::updatePhpFiles($dir_level, $php_files_json);
return self::includeMatchingFiles($dir_level, $php_files_json, $class_file_name);
}
} else {
self::updatePhpFiles($dir_level, $php_files_json);
return self::includeMatchingFiles($dir_level, $php_files_json, $class_file_name);
}
}
}
/**
* Register autoloader.
*/
spl_autoload_register(function ($className) {
autoload::include_system_files(WP_CONTENT_DIR, $className);
});