【问题标题】:Extended class not found when Base class is in a separate include file基类位于单独的包含文件中时找不到扩展类
【发布时间】:2009-09-01 22:28:28
【问题描述】:

这不起作用:

test.php:

include_once('test-include.php');  

$main = new mainClass();

//======================================================================
class mainClass { 
   function __construct() {
      $test2 = new Test2();
      echo $test2->var;
   }
}

//======================================================================
class Test2 extends Test1 { // test2
  var $var = 'b';
}

test-include.php:

// this does get printed out, so I know the include statement is working
echo 'DEBUG: this is the test-include.php file<br>'; 

//======================================================================
class Test1 { // test1
  var $var = 'a';
}

它给出了以下错误

PHP Fatal error:  Class 'Test2' not found in /path/to/test.php on line 8

这确实有效

test2.php:

// this is in the same position as the include statement in test.php
//======================================================================
class Test1 { // test1
  var $var = 'a';
}

$main = new mainClass();

//======================================================================
class mainClass { 
   function __construct() {
      $test2 = new Test2();
      echo $test2->var;
 }
}

//======================================================================
class Test2 extends Test1 { // test2
  var $var = 'b';
}

为什么将基类 (Test1) 放入包含文件会导致找不到扩展它的子类?换句话说,第一个示例失败了,因为当我们尝试实例化它时它找不到 Test2。这是有道理的,因为我们还没有进入代码执行流程中的 Test2。但是,在第二个示例中(没有 include 语句)没有错误,即使它是类似的情况(我们还没有在代码执行中到达 Test2 类)

哦,这是低于 5.1.6 的版本。

更新:

好的,Daff 是正确的 - 如果我移动

$main = new mainClass();

到 test.php 示例的最后,它可以工作。如果上面的行不在末尾,我仍然想知道为什么它不起作用 - 它在 test2.php 示例中工作得很好,该示例末尾没有 $main = new mainClass() 行.

更新 2:

好的,我尝试使用 require, require_onceinclude 代替 include_once - 这些都不起作用。而且我还在 test-include.php 文件中添加了一个测试回显语句,它被打印出来(而且我没有收到关于不存在的包含文件的错误)所以我知道包含语句正在工作。

【问题讨论】:

  • 您确定包含工作正常吗?
  • 它是如何失败的?编译错误,执行错误,没有错误但结果错误?
  • 如果你使用“require”,你会看到什么?如果你输入“echo 'This is test-include.php';”你会看到什么在“test-include.php”的开头? “test-include.php”是否在同一目录中?它在您的包含路径中吗?

标签: php oop


【解决方案1】:

这应该与定义顺序有关,并且在您实际使用它们之前应该包含每个类。如果你打电话给

$main = new mainClass();

在脚本结束时,即使使用包含文件,它也可以正常工作,因为所有类都已定义。最后你应该看看PHP autoload 函数,因为你会用一个小函数解决这些问题。

【讨论】:

  • 我认为部分问题是两个示例中的类定义顺序相同,但一个有效,另一个无效。
  • 是的,Alan 是正确的,我已经修改了 test2.php(并对其进行了测试)以将基类 (Test1) 与包含语句在 test.php - test2 中的位置相同。在这种情况下,php 仍然可以工作,所以这不是顺序问题,除非 PHP 包含不像我想象的那样工作(即,包含文件中的代码插入到 include 语句所在的位置)。
  • 好的定义顺序是更好的词。我仍然建议在任何处理开始之前自动加载或至少包括所有类文件。
  • 喜欢答案的伙伴,继续努力。尽管这对你来说很简单,但这并不是我凭直觉就能知道的。编辑:这显然仍在帮助人们三年 XD。
【解决方案2】:

好的,我想我可能已经想通了。根据这个错误报告:

http://bugs.php.net/bug.php?id=30453

PHP 4 允许在使用类后定义类,但对于 PHP 5,用 bug 线程的结尾海报的话来说:

PHP5 支持[声明类 使用后] 用于向后 兼容性,但我们不计划 支持所有组合。

所以我猜这个特殊情况是那些不受支持的组合之一。

【讨论】:

    猜你喜欢
    • 2013-08-09
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多