【发布时间】:2013-02-22 19:29:02
【问题描述】:
我正在使用 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 全局变量之前检查它是否是一个对象之外,最好的实现方法是什么?
【问题讨论】: