【问题标题】:Use non-namespaced library in php在 php 中使用非命名空间库
【发布时间】: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"

标签: php oop spl


【解决方案1】:

在加载之前尝试使用class_exists()

【讨论】:

  • 谢谢。我将 if (file_exists($file) 更改为 if (file_exists($file) && !class_exists($class))。就像一个魅力 :)
【解决方案2】:

您可以使用spl_autoload_register 注册多个自动加载器。这样你就可以为你自己的类和库编写自动加载器。它们一个接一个地触发并且应该返回truefalse - 如果加载成功与否。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2016-12-13
    • 2014-09-18
    • 1970-01-01
    • 2016-01-05
    • 2015-03-15
    相关资源
    最近更新 更多