0

名前空間の使用を開始し、いくつかのドキュメントを読みましたが、何か間違っているようです。

まず、次のように構築されたアプリケーション構造です。

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

それが私が望むものだと思います。しかし、クラスはロードされておらず、何も起こっていません。私は明らかに何かが欠けていますが、それを理解できないようです。皆さんはそれを見て、なぜこれが機能しないのか説明してもらえますか?

4

2 に答える 2

4

ここでの問題は、コールバック関数を に登録していないことです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");
于 2015-03-02T10:15:02.087 に答える
0

これはあなたが意味するものではありません:

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

そうすれば、次のようなクラスを呼び出すことができます。

$user = new User(); // And loads it from "ROOT"/classes/User.php
于 2015-03-02T10:20:00.277 に答える