spl_autoload没有加载任何类

时间:2015-02-26 10:02:44

标签: php namespaces autoloader spl-autoload-register spl-autoloader

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

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

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

这就是我想要的。但是没有加载类,也没有发生任何事情。我显然遗漏了一些东西,但我似乎无法弄明白。你们可以看看它并向我解释为什么这不起作用吗?

2 个答案:

答案 0 :(得分:4)

这里的问题是,您没有使用spl_autoload_register()注册回调函数。看看官方docs

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

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

答案 1 :(得分:0)

这不是你的意思:

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

这样你就可以调用类:

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