2012-12-18 53 views
1

我有一個項目是這樣的:PHP的自動加載的項目

project

現在我想在自動加載該文件夾類別和子文件夾中的所有PHP文件。

我可以做到這一點的:

$dirs = array(
    CMS_ROOT.'/classes', 
    CMS_ROOT.'/classes/layout', 
    CMS_ROOT.'/classes/layout/pages' 
); 
foreach($array as $dir) { 
    foreach (glob($dir."/*.php") as $filename) { 
    require_once $filename; 
    } 
} 

但我不喜歡這樣。例如。

「佈局/頁/ a.php只會」 延長 「佈局/頁/ b.php」

現在因爲a.php只會在第一次加載我得到一個錯誤。你如何加載你的項目文件?類?

解決:)

現在這是我的代碼:

spl_autoload_register('autoloader'); 
function autoloader($className) { 
    $className = str_replace('cms_', '', $className); 
    $className = str_replace('_', '/', $className); 

    $file = CLASSES.'/'.$className.'.php'; 
    if(file_exists($file)) { 
    require_once $file; 
    } 
} 
+0

我想你是誤會「自動裝載」的概念:http://php.net/ manual/en/language.oop5.autoload.php - 此資源可能也有幫助:http://framework.zend.com/manual/1.12/en/zend.loader.autoloader.html – Niko

+0

那麼,如果你只是直奔牆,它並不總是很好。首先大概看一下PHP手冊,另見http://php.net/spl_autoload_register,並考慮如何將類名映射到文件名。 – hakre

回答

1

你應該試試這個

<?php 

spl_autoload_register('your_autoloader'); 

function your_autoloader($classname) { 
    static $dirs = array(
     CMS_ROOT.'/classes', 
     CMS_ROOT.'/classes/layout', 
     CMS_ROOT.'/classes/layout/pages' 
    ); 
    foreach ($dirs as $dir) { 
     if (file_exists($dir . '/'. $classname. '.php')) { 
      include_once $dir . '/' . $classname . '.php'; 
     } 
    } 
} 

註冊your_autoloaderspl_autoload_register()將通過每一次PHP解釋器被調用後你訪問一個類:

  • 尚未加載require_once()include_once()

  • 是不是PHP的一部分,內部構件

+0

謝謝!這是我的一個愚蠢的問題。我可以爲自己弄清楚,但沒有時間。非常感謝hek2mgl! :) – ItsJohnB