为了澄清,我的意思是这样的:
class foon {
private $barn = null;
public function getBarn() {
if (is_null($this->barn)) {
$this->barn = getBarnImpl();
}
return $this->barn;
}
}当你并不总是需要getBarn,并且getBarn特别昂贵(例如,有一个DB调用)时,这就特别好了。有没有什么方法可以避免条件呢?这会占用很多空间,看起来很难看,而且看到条件句消失总是很好的。有没有其他的范例来处理这种我看不见的延迟加载?
发布于 2012-01-06 06:41:03
通过使用php的__call()魔术方法,我们可以很容易地编写一个装饰器对象来拦截所有的方法调用,并缓存返回值。
有一次我做了这样的事情:
class MethodReturnValueCache {
protected $vals = array();
protected $obj;
function __construct($obj) {
$this->obj = $obj;
}
function __call($meth, $args) {
if (!array_key_exists($meth, $this->vals)) {
$this->vals[$meth] = call_user_func_array(array($this->obj, $meth), $args);
}
return $this->vals[$meth];
}
}然后
$cachedFoon = new MethodReturnValueCache(new foon);
$cachedFoon->getBarn();发布于 2012-01-06 06:14:28
我时不时地想知道这一点,但我肯定想不出一个。除非你想创建一个单独的函数来处理数组和反射属性查找。
发布于 2012-01-06 06:16:52
return ( $this->barn = $this->barn ? $this->barn : getBarn() );
或者php 5.3 (?)其一:
return ( $this->barn = $this->barn ?: getBarn() );
https://stackoverflow.com/questions/8750575
复制相似问题