我正在使用 spl_autoload 进行依赖注入。
spl_autoload_register(function ($class)
{
$cFilePath = _CLASSLIB_ . "/class.$class.php";
if(file_exists($cFilePath))
{
include($cFilePath);
}
else
{
die("Unable to include the $class class.");
}
});
这工作正常。但是,假设这些是我的课程:
class Test
{
public function foo()
{
echo "Here.";
}
}
和
class OtherTest
{
public function bar()
{
global $Test;
$Test->foo();
}
}
所以,在我的执行代码中:
<?php
$OT = new OtherTest(); //Dependency Injection works and loads the file.
$OT->bar();
?>
我会收到一个错误,因为 bar() 尝试在测试类中全局化(没有实例化,因此从未自动加载)。
除了在每个方法中尝试使用 $Test 全局变量之前检查它是否是一个对象之外,实现它的最佳方法是什么?