【问题标题】:PHP autoloader - $classname includes the entire folder path and not just the class name itself?PHP autoloader - $classname 包括整个文件夹路径,而不仅仅是类名本身?
【发布时间】:2015-10-07 00:08:49
【问题描述】:

我遵循 WordPress 的命名约定,其中一个类 My_Class 应该驻留在名为 class-my-class.php 的文件中。我在 WordPress 中使用了 this autoloader,由 Rarst 编写。如果我打印出 $class_name 变量,我会看到前缀 class 附加到文件夹名称而不是类文件。我之前使用的其他一些自动加载器也有同样的问题。我可以做一些字符串操作并得到我想要的,但我想知道确切的问题是什么。

可能出了什么问题?

【问题讨论】:

  • 你的代码是什么样的?你如何为 wordpress 实现自动加载器类?如果在构造函数中给出,自动加载器本身只会添加一个目录。否则它是自动加载器所在的实际目录。我猜你使用了错误的类名。
  • 我使用了一个应该遵循 WP 编码标准的自动加载器。它适用于任何一种方式。类名是对的。

标签: php wordpress oop namespaces autoloader


【解决方案1】:

我刚刚看了你链接到的这个自动加载器,我想说它应该在第 21 行,像这样:

$class_path = $this->dir . '/class-' . strtolower( str_replace( '_', '-', basename( $class_name ) ) ) . '.php';

basename 只取路径的文件部分+文件扩展名。

您还需要检查此自动加载器文件的位置,因为 $this->dir 设置为 DIR,即自动加载器文件所在的目录。

【讨论】:

  • 有效,包含类文件。但是我仍然收到一个找不到类的错误。
【解决方案2】:

使用灵活的加载器。 试试这个。

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');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多