【发布时间】: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_once 和 include 代替 include_once - 这些都不起作用。而且我还在 test-include.php 文件中添加了一个测试回显语句,它被打印出来(而且我没有收到关于不存在的包含文件的错误)所以我知道包含语句正在工作。
【问题讨论】:
-
您确定包含工作正常吗?
-
它是如何失败的?编译错误,执行错误,没有错误但结果错误?
-
如果你使用“require”,你会看到什么?如果你输入“echo 'This is test-include.php';”你会看到什么在“test-include.php”的开头? “test-include.php”是否在同一目录中?它在您的包含路径中吗?