<?php/** * 所有观察者必须实现的接口 * Interface Observer */interface Observer { public function update();}/** * 观察者1 * Class sendEmail */class SendEmail implements Observer { public function update() { echo 'the email has been send <br>'; }}/** * 观察者2 * Class SaveName */class SaveName implements Observer { public function update() { echo 'the name has been save <br>'; }}/** * 被观察者接口 * Interface Observered */interface Observered { public function attach($object); public function delete($object); public function notify();}/** * 被观察者 * Class User */class User implements Observered { public $observers = array(); /** * 注册观察者 * @param $object */ public function attach($object) { if (!is_object($object)) { exit('it is not an object'); } if ($object instanceof Observer) { if (!in_array($object,$this->observers)) { $this->observers[] = $object; } } else { echo get_class($object) . ' is disable <br>'; } } /** * 删除观察者 * @param $object */ public function delete($object) { if (in_array($object,$this->observers)) { $index = array_search($object,$this->observers); unset($this->observers[$index]); } } /** * 通知所有观察者 */ public function notify() { foreach ($this->observers as $val) { $val->update(); } } /** * 被观察者自己的业务 */ public function printName() { echo 'I have been observing <br>'; }} $object = new User(); $object->attach(new SendEmail()); //注册观察者1 $object->attach(new SaveName()); //注册观察者2 $object->printName(); //被观察者自己的业务 $object->notify(); //通知所有的观察者