当Base类位于单独的包含文件中时,找不到扩展类

Bil*_*ill 7 php oop

这不起作用:

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';
}
Run Code Online (Sandbox Code Playgroud)

测试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';
}
Run Code Online (Sandbox Code Playgroud)

它给出以下错误

PHP Fatal error:  Class 'Test2' not found in /path/to/test.php on line 8
Run Code Online (Sandbox Code Playgroud)

这确实有效

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';
}
Run Code Online (Sandbox Code Playgroud)

为什么将Base类(Test1)放在包含文件中会导致无法找到扩展它的子类?换句话说,第一个例子是失败的,因为当我们尝试实例化它时它找不到Test2.这种方式很有意义,因为我们尚未在代码执行流程中使用Test2.但是,在第二个例子中(没有include语句)没有错误,即使它是类似的情况(我们还没有在代码执行中到达Test2类)

哦,这是在5.1.6版本.

更新:

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

$main = new mainClass();
Run Code Online (Sandbox Code Playgroud)

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

更新2:

好的,我已经尝试过使用require, require_onceinclude不是代替include_once- 这些都不起作用.我还在test-include.php文件中添加了一个测试echo语句并将其打印出来(加上我没有得到关于不存在的包含文件的错误)所以我知道include语句正在工作.

Daf*_*aff 6

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

$main = new mainClass();
Run Code Online (Sandbox Code Playgroud)

在脚本结束时,即使使用包含文件也能正常工作,因为已经定义了所有类.最后你应该看看PHP自动加载功能,因为你将通过一个小功能摆脱这些问题.