例如,这是我的网络结构,
index.php
'core/model/'
'core/helper/'
'core/ext/'
我在文件夹下有这些类文件model
,
MyClass.php
MyClass2.php
classfour.php
我想通过 Autoload 类自动加载它们,
define ('WEBSITE_DOCROOT', str_replace('\\', '/', dirname(__FILE__)).'/');
function autoloadMultipleDirectory($class_name)
{
// List all the class directories in the array.
$main_directories = array(
'core/model/',
'core/helper/',
'core/ext/'
);
$sub_directories = array();
$parts = explode('\\', $class_name);
$file_name = end($parts).'.php';
foreach($main_directories as $path_directory)
{
$iterator = new RecursiveIteratorIterator
(
new RecursiveDirectoryIterator(WEBSITE_DOCROOT.$path_directory), // Must use absolute path to get the files when ajax is used.
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $fileObject)
{
if ($fileObject->isDir())
{
$sub_directories[] = preg_replace('~.*?(?=core|local)~i', '', str_replace('\\', '/', $fileObject->getPathname())) .'/';
}
}
}
// Mearge the main dirs with any sub dirs in them.
$merged_directories = array_merge($main_directories,$sub_directories);
print_r($merged_directories);
// Loop the merge array and include the classes in them.
foreach($merged_directories as $path_directory)
{
if(file_exists(WEBSITE_DOCROOT.$path_directory.$file_name))
{
include WEBSITE_DOCROOT.$path_directory.$file_name;
}
}
}
实施,
spl_autoload_register('autoloadMultipleDirectory');
//define classone
class classone { }
//define classtwo
class classtwo { }
//define classthree
class classthree { }
print_r(get_declared_classes());
结果,
Array
(
[0] => stdClass
...
[131] => tidyNode
[132] => classone
[133] => classtwo
[134] => classthree
)
但是classfour
, MyClass
&MyClass2
不在列表中。
而对于,
$test = new MyClass();
$test2 = new MyClass2();
$test3 = new classfour();
将导致重复取决于我实例化了多少类,
Array
(
[0] => core/model/
[1] => core/helper/
[2] => core/ext/
)
Array
(
[0] => core/model/
[1] => core/helper/
[2] => core/ext/
)
Array
(
[0] => core/model/
[1] => core/helper/
[2] => core/ext/
)
在我的实时服务器中,我得到了更奇怪的结果,
Array
(
[0] => core/model/
[1] => core/helper/
[2] => core/ext/
[3] => core/model/./ (duplicated)
[4] => core/model/../ (duplicated)
[5] => core/helper/./ (duplicated)
[6] => core/helper/../ (duplicated)
[7] => core/ext/./ (duplicated)
[8] => core/ext/../ (duplicated)
)
知道为什么以及如何解决它吗?
编辑:
如果我手动包含这些类,
include 'core/model/MyClass.php';
include 'core/model/MyClass2.php';
include 'core/model/classfour.php';
print_r(get_declared_classes());
$test = new MyClass();
$test2 = new MyClass2();
$test3 = new classfour();
我得到正确答案,
Array
(
[0] => stdClass
...
[131] => tidyNode
[132] => classone
[133] => classtwo
[134] => classthree
[135] => MyClass
[136] => MyClass2
[137] => classfour
)
classfour
, MyClass
&MyClass2
现在在列表中。
怎么来的!??