【发布时间】:2013-04-26 14:24:52
【问题描述】:
我正在编写一个应用程序,其中所有类都使用命名空间,并使用 spl_autoload_register() 动态加载所有类。
现在我想使用一个非命名空间库 (WideImage)。由于 WideImage 不使用命名空间,因此 spl_autoload_register() 不起作用。所以手动包含脚本:
require( 'Library/WideImage/WideImage.php');
$w = new WideImage();
但它仍然会尝试自动加载;并给出一个致命的类未找到错误。
如何覆盖此自动加载功能?
根据要求:
spl_autoload_register(function( $class ) {
$path = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . CMS_PATH . DIRECTORY_SEPARATOR;
$classFile = str_replace( '\\', DIRECTORY_SEPARATOR, $class );
$classPI = pathinfo( $classFile );
$classPath = $path . $classPI[ 'dirname' ] ;
$file = $classPath . DIRECTORY_SEPARATOR . $classPI[ 'filename' ] . '.class.php';
if (file_exists($file)) {
require_once( $file );
}
});
编辑:解决方案:
改变
if (file_exists($file)
to
if (file_exists($file) && !class_exists($class)) {
【问题讨论】:
-
把它移到你的自动加载目录之外或者给它一个命名空间?
-
粘贴自动加载功能的代码。
-
@Dave:改变路径并没有什么不同。将命名空间添加到 WideImage 将意味着遍历所有类、更改文件名等。不想每次更新都这样做:)
-
autoloader中的IF Statement应该可以解决它。在那里你可以检查你的$class = "WideImage"。