当访问不存在的成员时,自动创建对象。
$obj = new ClassName();
$newObject = $ojb->nothisobject;有可能吗?
发布于 2010-02-21 16:35:38
您可以使用Interceptor __get()实现这种功能。
class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}尽管上一篇文章中的示例在属性更改为public时也能正常工作,所以您可以从外部访问它。
发布于 2010-02-21 16:15:24
使用幻数重载函数
发布于 2010-02-21 16:16:44
如果您的意思是惰性initalization,这是许多方法中的一种:
class SomeClass
{
private $instance;
public function getInstance()
{
if ($this->instance === null) {
$this->instance = new AnotherClass();
}
return $this->instance;
}
}https://stackoverflow.com/questions/2306467
复制相似问题