<?php //定义接口,观察者统一的方法,便于subject调用通知 interface Observerable { public function update(); } //定义观察者1 class Observer1 implements Observerable { public function update() { echo "我是观察者1"; } } //定义观察者2 class Observer2 implements Observerable { public function update() { echo "我是观察者2"; } } // 主题,被观察的目标 class Subject { private $observer_list = array(); // 注册观察者 public function reg_observer($observer) { if(!in_array($observer,$this->observer_list)) { $this->observer_list[] = $observer; } } // 向观察者发送消息,告诉它主题有改变 public function notify() { if(!empty($this->observer_list)) { foreach($this->observer_list as $ob) { $ob->update(); } } } } $ob1 = new Observer1(); $ob2 = new Observer2(); $subj = new Subject(); // 注册观察者 $subj->reg_observer($ob1); $subj->reg_observer($ob2); // 向观察者推送消息 $subj->notify();