我正在使用spl_autoload进行依赖注入。PHP:我怎样才能让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();
?>
我会得到一个错误,因为巴()尝试测试类中的全局(未实例化,因此从未自动加载)。
除了在尝试在每种方法中使用它之前检查$ Test全局是否是对象之外,实现这一点的最佳方式是什么?
谢谢,克里斯!我最终完成的工作是设置构造函数,以便可以使用一组类名和对象作为键/值对来重载它,通过switch语句运行它并将其分配给类中相应的受保护属性。 – Tealstone 2013-02-22 20:24:45