加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在延迟加载中避免条件

发布时间:2020-12-13 18:07:59 所属栏目:PHP教程 来源:网络整理
导读:只是为了澄清,我的意思是: class foon { private $barn = null; public function getBarn() { if (is_null($this-barn)) { $this-barn = getBarnImpl(); } return $this-barn; }} 当你不总是需要getBarn时,这是特别好的,并且getBarn特别昂贵(例如有一个DB调
只是为了澄清,我的意思是:
class foon {
   private $barn = null;

   public function getBarn() {
      if (is_null($this->barn)) {
         $this->barn = getBarnImpl();
      }
      return $this->barn;
   }
}

当你不总是需要getBarn时,这是特别好的,并且getBarn特别昂贵(例如有一个DB调用).有没有办法避免有条件的?这占用了大量空间,看起来很丑陋,看到条件消失总是很好.还有其他一些范例可以处理这个我看不到的延迟加载吗?

通过使用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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读