【问题标题】:Php: how to resolve "Cannot redeclare class" when there's no "previously declared"PHP:当没有“先前声明”时如何解决“无法重新声明类”
【发布时间】:2012-06-26 12:46:23
【问题描述】:

我想测试phpDocumentor-alpha,有一个问题,有些人似乎没有有:

# sudo pear uninstall phpdoc/phpDocumentor-alpha
uninstall ok: channel://pear.phpdoc.org/phpDocumentor-2.0.0a6
olivier@olivier-ubuntu ~/Documents/pizzas/dev # phpdoc --help
bash: /usr/bin/phpdoc: Aucun fichier ou dossier de ce type
# 
# sudo pear install --alldeps -f phpdoc/phpDocumentor-alpha
downloading phpDocumentor-2.0.0a6.tgz ...
Starting to download phpDocumentor-2.0.0a6.tgz (1,107,853 bytes)
..................................done: 1,107,853 bytes
install ok: channel://pear.phpdoc.org/phpDocumentor-2.0.0a6
# phpdoc --help
PHP Fatal error:  Cannot redeclare class phpDocumentor\Plugin\Core\Listener in /usr/share/php/phpDocumentor/src/phpDocumentor/Plugin/Core/Listener.php on line 194

Fatal error: Cannot redeclare class phpDocumentor\Plugin\Core\Listener in /usr/share/php/phpDocumentor/src/phpDocumentor/Plugin/Core/Listener.php on line 194
# 

好的,我可以通过以下方式避免这个问题:

if ( !class_exists('MTIHelperEstadosLocal') ) {...}

但这只是一个丑陋的解决方法。我想知道是否有办法知道声明的初始位置(= 其中包含或其他)。

有什么想法吗?

【问题讨论】:

标签: php


【解决方案1】:

这是一个简单的解决方案:

print_r(get_declared_classes());

【讨论】:

  • 太好了,这告诉我第一个包含来自作曲家自动加载。
【解决方案2】:

在文件{path-to-pear-directory}/PEAR/phpDocumentor/vendor/composer/ClassLoader.php中,第150行是:

require $file;

简单地改成

require_once $file;

【讨论】:

  • 这并没有“解决”问题,它只是通过解决方法阻止它发生。用户应该找到有问题的代码并修复它,例如两次使用“require”是错误的编码,并且可能是错误的代码库设计或结构。这应该得到妥善解决。这个建议有点像使用@ 来“解决”警告或通知消息。
【解决方案3】:

根据您的操作系统以及您构建文档根路径的方式,路径名称中的大写字母与小写字母可能存在问题。这经常让我在大型 CMS 项目上绊倒,例如 Mac OSX 上的 drupal

// Insert this debug code before require statement.
if (class_exists('classInQuestion')) {
  $reflector = new ReflectionClass('classInQuestion');
  echo $reflector->getFileName() . ' ' . $reflector->getStartLine() . "\n";
  echo $newClassFile;
  exit();
}
// Normal pre-existing require statement
require_once $newClassFile

【讨论】:

    【解决方案4】:

    除了所有答案之外,您还可以考虑使用 php 声明的类。例如点网。当我明确定义一个名为 Dotnet 的类以使用 Dotnet 二进制文件时,它会在创建该类的第一个实例时引发错误。

    如果你要使用自己修改过的类而不是 php 呈现给你的类,你应该给它们起可区分的名字。

    【讨论】:

      猜你喜欢
      • 2019-03-23
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多