簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM