<table cellspacing="0" cellpadding="0"><tr><td class="t_f" id="postmessage_47990"> <div class="blockcode"> <div id="code_yHb"><ol> <li> <li>class DemoSubject implements SplSubject{</li> <li> private $observers, $value;</li> <li> </li> <li> public function __construct(){</li> <li> $this->observers = array();</li> <li> }</li> <li> </li> <li> public function attach(SplObserver $observer){</li> <li> $this->observers[] = $observer;</li> <li> }</li> <li> </li> <li> public function detach(SplObserver $observer){</li> <li> if($idx = array_search($observer, $this->observers, true)){</li> <li> unset($this->observers[$idx]);</li> <li> }</li> <li> }</li> <li> </li> <li> public function notify(){</li> <li> foreach($this->observers as $observer){</li> <li> $observer->update($this);</li> <li> }</li> <li> }</li> <li> </li> <li> public function setValue($value){</li> <li> $this->value = $value;</li> <li> $this->notify();</li> <li> }</li> <li> </li> <li> public function getValue(){</li> <li> return $this->value;</li> <li> }</li> <li>}</li> <li> </li> <li>class DemoObserver implements SplObserver{</li> <li> public function update(SplSubject $subject){</li> <li> echo 'The new value is '. $subject->getValue();</li> <li> }</li> <li>}</li> <li> </li> <li>$subject = new DemoSubject();</li> <li>$observer = new DemoObserver();</li> <li>$subject->attach($observer);</li> <li>$subject->setValue(5);</li> </ol></div> <em onclick="copycode($('code_yHb'));">复制代码</em> </div> </td></tr></table> <div id="comment_47990" class="cm"> </div> <div id="post_rate_div_47990"></div> <br><br>