访问不存在的成员时,自动创建对象。
$obj = new ClassName();
$newObject = $ojb->nothisobject;
是否可以?
使用神奇的重载函数
如果您的意思是惰性初始化,这是多种方法之一:
class SomeClass
{
private $instance;
public function getInstance()
{
if ($this->instance === null) {
$this->instance = new AnotherClass();
}
return $this->instance;
}
}
您可以使用 Interceptor __get() 实现这种功能
class ClassName
{
function __get($propertyname){
$this->{$propertyname} = new $propertyname();
return $this->{$propertyname}
}
}
虽然上一篇文章中的示例在属性更改为公共时也可以正常工作,因此您可以从外部访问它。
$obj = new MyClass();
$something = $obj->something; //instance of Something
使用以下延迟加载模式:
<?php
class MyClass
{
/**
*
* @var something
*/
protected $_something;
/**
* Get a field
*
* @param string $name
* @throws Exception When field does not exist
* @return mixed
*/
public function __get($name)
{
$method = '_get' . ucfirst($name);
if (method_exists($this, $method)) {
return $this->{$method}();
}else{
throw new Exception('Field with name ' . $name . ' does not exist');
}
}
/**
* Lazy loads a Something
*
* @return Something
*/
public function _getSomething()
{
if (null === $this->_something){
$this->_something = new Something();
}
return $this->_something;
}
}