存在しないメンバーにアクセスすると、自動的にオブジェクトを作成します。
$obj = new ClassName();
$newObject = $ojb->nothisobject;
出来ますか?
魔法のオーバーロード関数を使用する
遅延初期化を意味する場合、これは多くの方法の 1 つです。
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;
}
}