【发布时间】:2011-12-04 12:17:55
【问题描述】:
跟进此question,似乎只需使用下面的__autoload 代码即可解决重复问题,
function __autoload($class_name)
{
include AP_SITE."classes_1/class_".$class_name.".php";
}
$connection = new database_pdo(DSN,DB_USER,DB_PASS);
var_dump($connection);
结果,
object(database_pdo)[1]
protected 'connection' =>
object(PDO)[2]
但是这只从一个目录加载类,其他目录呢?因为我将类分组在不同的目录中。所以如果我想从其他目录加载类,我会得到错误,
function __autoload($class_name)
{
include AP_SITE."classes_1/class_".$class_name.".php";
include AP_SITE."classes_2/class_".$class_name.".php";
}
消息,
警告: 包括(C:/wamp/www/art_on_your_doorstep_2011_MVC/global/applications/CART/classes_2/class_database_pdo.php) [function.include]:无法打开流:没有这样的文件或目录 在...
指的是这一行 - include AP_SITE."classes_2/class_".$class_name.".php";
所以,我的问题是 - 如何使用 __autoload 从多个目录加载类?
一种可能的解决方案:
function autoload_class_multiple_directory($class_name)
{
# List all the class directories in the array.
$array_paths = array(
'classes_1/',
'classes_2/'
);
# Count the total item in the array.
$total_paths = count($array_paths);
# Set the class file name.
$file_name = 'class_'.strtolower($class_name).'.php';
# Loop the array.
for ($i = 0; $i < $total_paths; $i++)
{
if(file_exists(AP_SITE.$array_paths[$i].$file_name))
{
include_once AP_SITE.$array_paths[$i].$file_name;
}
}
}
spl_autoload_register('autoload_class_multiple_directory');
【问题讨论】: