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

PHP观察者模式示例【Laravel框架中有用到】

发布时间:2020-12-14 20:05:21 所属栏目:大数据 来源:网络整理
导读:本篇章节讲解PHP观察者模式。供大家参考研究具体如下: _observers = array(); } //增加一个观察者对象 public function attach(Observer $observer) { return array_push($this->_observers,$observer); } //删除一个已经注册过的观察者对象 publ

本篇章节讲解PHP观察者模式。分享给大家供大家参考,具体如下:

_observers = array(); } //增加一个观察者对象 public function attach(Observer $observer) { return array_push($this->_observers,$observer); } //删除一个已经注册过的观察者对象 public function detach(Observer $observer) { $index = array_search($observer,$this->_observers); if($index === false || !array_key_exists($index,$this->_observers)) return false; unset($this->_observers[$index]); return true; } //通知所有注册过的观察者 public function notifyObservers() { if(!is_array($this->_observers)) return false; foreach($this->_observers as $observer) { $observer->update(); } return true; } } //抽象观察者角色 interface Observer { //更新方法 public function update(); } //观察者实现 class ConcreteObserver implements Observer { private $_name; public function __construct($name) { $this->_name = $name; } //更新方法 public function update() { echo 'Observer'.$this->_name.' has notify'; } } $Subject = new ConcreteSubject(); //添加第一个观察者 $observer1 = new ConcreteObserver('baixiaoshi'); $Subject->attach($observer1); echo 'the first notify:'; $Subject->notifyObservers(); //添加第二个观察者 $observer2 = new ConcreteObserver('hurong'); echo '
second notify:'; $Subject->attach($observer2); /*echo $Subject->notifyObservers(); echo '
'; $Subject->notifyObservers();*/ ?>

运行结果:

the first notify:Observerbaixiaoshi has notify second notify:

更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》

希望本文所述对大家PHP程序设计有所帮助。

(编辑:李大同)

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

    推荐文章
      热点阅读