【问题标题】:Cannot redeclare class + class not found?无法重新声明类+找不到类?
【发布时间】:2011-06-27 21:04:04
【问题描述】:

我今天在使用 php 时遇到了一些非常奇怪的错误。

我为 A/B 测试编写了一个小类,并想在我的 php 文档中创建一个新实例:

if(!class_exists('ab_tester')) include('../lib/php/ab_tester.php');
$ab = new ab_tester($user['id']);

有人会认为这应该可以解决问题,但 php 说:

Fatal error: Cannot redeclare class ab_tester in [PATH_TO_PHP]ab_tester.php on line 10

为什么会这样?

注意:ab_tester.php 的第 10 行如下所示:

class ab_tester {

如果我离开包含行,创建一个新的 ab_tester 实例,它会吐出:

Fatal error: Class 'ab_tester' not found in [PATH_TO_PHP]returning.php on line 25

我现在该怎么办?如果我尝试导入它,它已经存在,如果我不导入,它就丢失了。

【问题讨论】:

  • class ab_tester 在您的类文件中出现多次吗?可能是这样...
  • 不,它没有。然后错误不会在文件的开头抛出,我想:/
  • 你能告诉我们你文件的前 10 行吗?
  • 找到了。在代码河下游的包含文件(returning.php)中,还有另一个类文件的“包含”。可悲的是,PHP 调试器在类文件本身中指出了错误。这没有帮助=]

标签: php class include


【解决方案1】:

ab_tester.php 中的前 9 行代码包含什么?

我敢打赌那里有另一个class ab_tester(或者在包含中,无论如何)

编辑:

另一种可能的解释是,您稍后在 returning.php 的代码上进行了第二次包含 ab_tester.php。所以即使你在这个特定的行中使用include_once,第二个调用仍然只是一个include...

【讨论】:

  • 不,一点也不。它包含 PHPDoc。
【解决方案2】:

怎么样:

include_once('../lib/php/ab_tester.php');
$ab = new ab_tester($user['id']);

?

【讨论】:

  • include_once 与 include => cannot redeclare 的作用相同……我使用 php 的这些年来从未见过这样的行为!
【解决方案3】:

尝试自动加载类而不是使用包含?

function __autoload($class_name){
    $class_name = strtolower($class_name);
    $path = "../includes/{$class_name}.php";
    if(file_exists($path)){
        require_once($path);
    }else{
        die("The file {$class_name}.php could not be found.");
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2013-08-07
    • 1970-01-01
    • 2011-03-22
    • 2023-03-29
    • 2016-02-24
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多