我自动加载我的类,并希望在使用时动态实例化类。使用__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