我自動加載我的類,並希望在使用時動態實例化類。使用__set和__get魔術方法實例化類
而不是在我的父類中有20個類實例化,我想要一個方法來實例化一個類時被調用。
例如:
$this->template->render();
將實例
$this->template = new Template();
我嘗試這個
public function __set($name, $value)
{
return $this->$name;
}
public function __get($name)
{
$this->$name = new $name();
}
這似乎並不工作,但我也覺得我這樣做錯誤。
我弄不清楚的一個問題是我的類位於\ System命名空間中。我似乎無法解決new "\System".$name()
或new \System.$name()
而沒有出現錯誤;
是有辦法不多自動創建屬性如何,您可以在__construct()方法創建一個屬性? – Eli 2012-04-19 21:01:22
你已經想要命名你的「虛擬」屬性'template',因此命名真正的屬性並不明智。 – KingCrunch 2012-04-19 21:02:31
不應該'__set()'方法設置一些東西而不是返回一些東西? – 2012-04-19 21:11:59