我遵循WordPress的命名约定,其中类My_Class
应该驻留在名为class-my-class.php
的文件中。我使用了Rarst编写的WordPress自动加载器。如果我打印出$class_name
变量,我看到前缀class
被附加到文件夹名称而不是类文件。我之前用过的其他自动装填机也有同样的问题。我可以做一点字符串操作,得到我想要的,但我想知道到底是什么问题。
怎么了?
我刚刚看了一下你链接的这个自动加载器,我想它应该在第21行,像这样:
$class_path = $this->dir . '/class-' . strtolower( str_replace( '_', '-', basename( $class_name ) ) ) . '.php';
basename
只接受路径的文件部分+文件扩展名。
您还需要检查自动加载器文件的位置,因为$this->dir被设置为 dir ,这是自动加载器文件所在的目录。
使用灵活的加载器。试试这个
function TR_Autoloader($className)
{
$assetList = array(
get_stylesheet_directory() . '/vendor/log4php/Logger.php',
// added to fix woocommerce wp_email class not found issue
WP_PLUGIN_DIR . '/woocommerce/includes/libraries/class-emogrifier.php'
// add more paths if needed.
);
// normalized classes first.
$path = get_stylesheet_directory() . '/classes/class-';
$fullPath = $path . $className . '.php';
if (file_exists($fullPath)) {
include_once $fullPath;
}
if (class_exists($className)) {
return;
} else { // read the rest of the asset locations.
foreach ($assetList as $currentAsset) {
if (is_dir($currentAsset)) {
foreach (new DirectoryIterator($currentAsset) as $currentFile) {
if (!($currentFile->isDot() || ($currentFile->getExtension() <> "php")))
require_once $currentAsset . $currentFile->getFilename();
}
} elseif (is_file($currentAsset)) {
require_once $currentAsset;
}
}
}
}
spl_autoload_register('TR_Autoloader');