简单的问题,但我不知道这是否真的可能..
例子:
类测试有一个像这样的 spl_autoload_register:
function __construct() {
spl_autoload_register(function ($class) {
echo "{$this->projectroot}/include/{$class}.php";
require_once(strtolower("{$this->projectroot}/classes/{$class}.php"));
});
}
$projectroot 是一个对象范围变量,带有项目目录的路径。
我在我的项目中包含类测试,从中创建一个新实例:
$test = new test();
现在我希望 $test 在创建时加载一个带有函数的类文件:
$test2 = new test2();
其中 test2 是 /include/test2.php 中名为 test2 的类。
当我尝试这样做时,它给了我一个错误说:
Fatal error: Using $this when not in object context in
但是当我尝试时:
$test2 = new $test1->test2();
它完全忽略了 test1 中的 spl_autoload_register 函数:/ 只是说明显然 test2 不是已知方法(未定义的属性)。
有没有办法在我的项目的类测试中使用 spl_autoload_register 函数,而无需在我的主项目中进一步定义它?
编辑
我使用全局变量“修复”了它,但我很好奇是否有一些 OOP 方法?(并不是说这是实用/最佳实践 OOP 使用...)只是好奇。