spl_autoloader未加载任何类


spl_autoloader not loading any classes

所以我已经开始使用名称空间并阅读了一些文档,但我似乎做错了什么。

首先是我的应用程序结构,它是这样构建的:

root
-dashboard(this is where i want to use the autoloader)
-index.php
--config(includes the autoloader)
--WePack(package)
---src(includes all my classes)

现在在src目录中,我包含了以下类:

namespace WePack'src;
class Someclass(){
}

config.php的内容是:

<?php
// Start de sessie
ob_start();
session_start();
// Locate application path
define('ROOT', dirname(dirname(__FILE__)));
set_include_path(ROOT);
spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();
echo get_include_path();

我在我的index.php 中这样使用它

require_once ('config/config.php');
use WePack'src;
$someclass = new Someclass;

这就是echo get_include_path();退货:

/home/wepack/public_html/dashboard

我想这就是我想要的。但是类没有被加载,并且什么都没有发生。我显然错过了什么,但我似乎想不通。你们能看一看并向我解释为什么这不起作用吗?

这里的问题是,您没有向spl_autoload_register()注册回调函数。看看官方文件。

为了更灵活,您可以编写自己的类来注册和自动加载类,如下所示:

class Autoloader
{
    private $baseDir = null;
    private function __construct($baseDir = null)
    {
        if ($baseDir === null) {
            $this->baseDir = dirname(__FILE__);
        } else {
            $this->baseDir = rtrim($baseDir, '');
        }
    }
    public static function register($baseDir = null)
    {
        //create an instance of the autoloader
        $loader = new self($baseDir);
        //register your own autoloader, which is contained in this class
        spl_autoload_register(array($loader, 'autoload'));
        return $loader;
    }
    private function autoload($class)
    {
        if ($class[0] === '''') {
            $class = substr($class, 1);
        }
        //if you want you can check if the autoloader is responsible for a specific namespace
        if (strpos($class, 'yourNameSpace') !== 0) {
            return;
        }
        //replace backslashes from the namespace with a normal directory separator
        $file = sprintf('%s/%s.php', $this->baseDir, str_replace('''', DIRECTORY_SEPARATOR, $class));
        //include your file
        if (is_file($file)) {
            require_once($file);
        }
    }
}

在这之后,你将注册你的自动加载器如下:

Autoloader::register("/your/path/to/your/libraries");

这不是你的意思吗:

spl_autoload_register(function( $class ) {
    include_once ROOT.'/classes/'.$class.'.php';
});

这样你就可以称一个类为:

$user = new User(); // And loads it from "ROOT"/classes/User.php