- <?php
- header("Content-Type: text/html;charset=utf-8");
- class test implements SplSubject{//被观察者类
-
- public $_observer;
- public $num;
- public $ad;
- function __construct()
- {
- $this->_observer = new SplObjectStorage();
- }
- public function run(){
- $this->notify();
- print_r($this);
- }
- public function attach(SplObserver $observer)
- {
- // TODO: 添加观察者对象
- $this->_observer->attach($observer);
- }
- public function detach(SplObserver $observer)
- {
- // TODO: Implement detach() method.
- $this->_observer->detach($observer);
- }
- public function notify()
- {
- // TODO: Implement notify() method.
- foreach ($this->_observer as $obj){
- $obj->update($this);
- }
- }
- }
- class checkNum implements SplObserver{
- public function update(SplSubject $subject)
- {
- // TODO: 根据通知更新
- $subject->num = "检查次数";
- }
- }
- class checkAd implements SplObserver{
- public function update(SplSubject $subject)
- {
- // TODO: 根据通知更新
- $subject->ad = "检查广告";
- }
- }
- $test = new test();
- $test->attach(new checkNum());
- $test->attach(new checkAd());
- $test->run();