且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP中的自动加载器-一次运行两个

更新时间:2023-02-02 09:51:40

这有点粗糙,但是实际上您只需要一个自动加载器即可检查多个目录:

This is a little rough, but you actually only need one autoloader that just checks within multiple directories:

abstract class Hakre_Theme_AutoLoader
{
    public static $directories;

    public static function init()
    {
        // configure paths
        self::$directories = array(
            get_template_directory(), // current theme, parent in case of childtheme
            get_stylesheet_directory(), // current theme, child in case of childtheme
        );

        // please double check if you really need to prepend
        return spl_autoload_register('Hakre_Theme_AutoLoader::autoload', true, true);
    }

    public static function autoload($class)
    {
        $filename = str_replace('_', '/', $class) . '.php';

        foreach (self::$directories as $directory) {
            $path = $directory . '/' . $filename;
            if (is_file($path)) {
                require($path);
                return; # leave because the class has been loaded
            }
        }
    }
}


Hakre_Theme_AutoLoader::init();

## If you're unsure all worked out properly:
var_dump(Hakre_Theme_AutoLoader::$directories);

实际上应该这样做,但是我还没有测试过.请参见var_dump,您可以调试是否注册了正确的目录.不必仅因为要签入两个目录就需要多个回调.

This should actually do it, however I've not tested it. See the var_dump, you can debug if the correct directories are registered or not. No need to have multiple callbacks only because you want to check in two directories.