我有一個項目是這樣的:PHP的自動加載的項目
現在我想在自動加載該文件夾類別和子文件夾中的所有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;
}
}
我想你是誤會「自動裝載」的概念:http://php.net/ manual/en/language.oop5.autoload.php - 此資源可能也有幫助:http://framework.zend.com/manual/1.12/en/zend.loader.autoloader.html – Niko
那麼,如果你只是直奔牆,它並不總是很好。首先大概看一下PHP手冊,另見http://php.net/spl_autoload_register,並考慮如何將類名映射到文件名。 – hakre