我看到自己做了很多这样的事情:
function getTheProperty()
{
if (! isset($this->theproperty)) {
$property = // logic to initialise thepropery
$this->theproperty = $property;
}
return $this->theproperty;
}
这很好,因为它避免了用于初始化值的epxensive逻辑。然而,到目前为止,我可以看到的缺点是,我无法确切地确定客户将如何使用它,这可能会令人困惑。
这是一个好用的模式吗?这样做时应该考虑哪些因素?
如何添加参数 - $ forceNew例如绕过memoization?
答案 0 :(得分:0)
Magic Methods。类似的东西:
Class MyMagic {
private $initinfo = array(
'foo' => array('someFunction', array('arg1', 'arg2'))
'bar' => array(array($this, 'memberFunction'), array('arg3'))
);
public function __get($name) {
if( ! isset($this->$name) ) {
if( isset($this->initinfo[$name]) ) {
$this->$name = call_user_func_array(initinfo[$name][0], initinfo[$name][1]);
} else {
throw new Exception('Property ' . $name . 'is not defined.');
}
} else {
return $this->$name;
}
}
}
$magic = new MyMagic();
echo $magic->foo; //echoes the return of: someFunction('arg1', 'arg2')
echo $magic->bar; //echoes the return of: $this->memberFunction('arg3')