簡體   English   中英

Spl_autoload_register()在服務器上不起作用

[英]Spl_autoload_register() not working on server

我使用spl_autoloader_register函數制作了一個簡單的自動加載器,它在我的虛擬服務器上運行良好,但是在服務器上,我僅收到“致命錯誤:找不到類'X'”。 我在帶有PHP 5.4的Mac上運行它,但它也可以在5.3版本的Windows / ubuntu中工作,與我的物理服務器相同。 我沒有SSH訪問權限。 這是我的自動加載代碼:

class Load
{   
    public static function autoload($class)
    {    
        $class = strtolower($class);        
        $lib =  $_SERVER['DOCUMENT_ROOT'] . BASENAME . "/libs/{$class}.php";        
        $model =  $_SERVER['DOCUMENT_ROOT'] . BASENAME . "/models/{$class}.class.php";  
        $controller =  $_SERVER['DOCUMENT_ROOT'] . BASENAME . "/controllers/{$class}.php";  

        if(is_readable($lib)){
            require_once $lib;  
        }elseif (is_readable($model)) {
            require_once $model;        
        }elseif (is_readable($controller)){
            require_once $controller;
        }
    }

}
spl_autoload_register("Load::autoload");

我一直在本地應用程序上使用spl,但是這是我第一次在服務器上嘗試使用它。 任何有關更好做法的建議都將有所幫助。 謝謝

一個好的做法是添加自己的包含路徑。 然后,您可以拒絕$ _SERVER ['DOCUMENT_ROOT']。 例如..

// Define path to library
define('MY_LIBRARY_PATH', realpath(dirname(__FILE__) . '/../insert_path_here_relativly'));

// Ensure library is on include_path
set_include_path(
    get_include_path() . PATH_SEPARATOR . MY_LIBRARY_PATH
);

然后是您的自動裝帶器。

class Load
{   
    public static function autoload($class)
    {    
        $class = strtolower($class);        
        $lib =  MY_LIBRARY_PATH . "/libs/{$class}.php";        
        $model = MY_LIBRARY_PATH . "/models/{$class}.class.php";  
        $controller = MY_LIBRARY_PATH . "/controllers/{$class}.php";  

        if(is_readable($lib)){
            require_once $lib;  
        }elseif (is_readable($model)) {
            require_once $model;        
        }elseif (is_readable($controller)){
            require_once $controller;
        }
    }

}
spl_autoload_register("Load::autoload");

暫無
暫無

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

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