2012-08-30 92 views
0

我正在更新我的代碼並試圖使用spl_autoload_register,但它很簡單,不工作! 我在Centos/Ubuntu/Win7上使用PHP 5.3.8 - Apache 2.22並嘗試回顯某些內容,但我沒有收到任何內容......一直試圖使其在最後3個小時內沒有任何結果...此操作正在讓我瘋狂!PHP spl_autoload_register什麼都不做

class ApplicationInit { 
    // Constructor 
    public function __construct() { 
     spl_autoload_register(array($this, 'classesAutoloader')); 
     echo 'construct working...!'; 
    } 

    // Autoloading methods 
    public function classesAutoloader($class) { 
     include 'library/' . $class . '.php'; 

     echo 'autoload working...!'; 
    } 
} 

從__construct作品,但「classesAutoloader」不工作的時候第一個回波,這個類是在一個文件夾中的PHP文件中定義的,我從喜歡的index.php以下稱之爲:

define('DS', DIRECTORY_SEPARATOR); 
define('ROOT', getcwd() . DS); 
define('APP', ROOT . 'application' . DS); 

// Initializing application 
require(APP.'appInit.php'); 
$classAuto = new ApplicationInit(); 

任何幫助是真正感激,在此先感謝!

+0

您是否看到''構造工作......!'? –

+0

它沒有做任何事情,因爲你不想引用任何未加載的類。在'$ classAuto'之後,添加一些類似'new SomeClassThatDoesntExist()'的東西,你會看到'classsesAutoloader()'試圖加載一些不會退出的類。 – nickb

+0

是的,我這樣做,謝謝你的回答,但是......做你剛剛所說的話,對我來說,就像做文件包括沒有spl_autoload_register一樣...... – CABP

回答

1

看起來好像你在做錯事。您傳遞給spl_autoload_register的函數是負責加載類文件的函數。

您的代碼調用

$classAuto = new ApplicationInit(); 

,但到那個時候,ApplicationInit已經被加載,從而自動加載功能不被調用

一個更合乎邏輯的方法將是你打電話

spl_autoload_register(function($class){ 
    include 'library/' . $class . '.php'; 
}); 

然後當你調用

$something = new MyClass(); 

MyClass未定義,那麼它會調用你的函數來加載該文件並定義類。

+0

我不認爲他的問題是'ApplicationInit'類沒有加載,但其他類不是......我認爲*你的*答案是100%錯誤的,而不是我的主題。 –

+0

所以,我應該直接從index.php中使用spl_autoload_register吧?如果我這樣做,我如何將'ApplicationInit'函數傳遞給$ class參數? – CABP

+0

@CABP你所擁有的代碼,就像它(我會使用我在回答中建議的)那樣奇怪,應該是有效的。沒有任何事情發生的原因是因爲你沒有嘗試自動加載任何類。爲了工作,你需要調用新的MyCustomClass(),然後它會在你的庫文件夾中尋找MyCustomClass.php –

1

你的問題是什麼?你的代碼工作正常。

class ApplicationInit { 
    public function __construct() { 
     spl_autoload_register(array($this, 'classesAutoloader')); 
     echo 'construct working...!'; 
    } 

    public function classesAutoloader($class) { 
     include 'library/' . $class . '.php'; 

     echo 'autoload working...!'; 
    } 
} 

$classAuto = new ApplicationInit(); //class already loaded so dont run autoload 

$newclass = new testClass(); //class not loaded so run autoload