我正在使用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