php的观察者设计模式实现相对简单,但是php5+版本中已经有标准库类库支持,我们只需简单继承并实现就可以了。
观察者:实现标准接口类库SplSubject。一个注册方法:attach,一个取消注册方法:detach。一个通知方法:nofity。
立即学习“PHP免费学习笔记(深入)”;
<?phpclass TSPLSubject implements SplSubject{ private $observers, $value; public function __construct(){ $this->observers =array(); } public function attach(SplObserver $observer){ $this->observers[] = $observer; } public function detach(SplObserver $observer){ if($idx = array_search($observer, $this->observers,true)) { unset($this->observers[$idx]); } } /** * * Notify observers one by one (main entry) * * @param none * @return none */ public function notify(){ foreach($this->observers as $observer){ $observer->update($this); } } public function setValue($value){ $this->value = $value; //$this->notify(); } public function getValue(){ return $this->value; }}立即学习“PHP免费学习笔记(深入)”;
立即学习“PHP免费学习笔记(深入)”;
<?phpclass TSPLObserver implements SplObserver{ public function update(SplSubject $subject){ echo 'The new state of subject ' , nl2br("\r\n");// echo 'The new state of subject '.$subject->getValue(); }}<?phpclass TSPLObserver1 implements SplObserver{ public function update(SplSubject $subject){ echo 'The new state of subject one ' , nl2br("\r\n");// echo 'The new state of subject '.$subject->getValue(); }}立即学习“PHP免费学习笔记(深入)”;
立即学习“PHP免费学习笔记(深入)”;
<?phpfunction __autoload($classname) { require_once ($classname . ".php"); }$subject = new TSPLSubject();$subject->attach(new TSPLObserver());$observer1 = new TSPLObserver1();$subject->attach($observer1);//$subject->attach(new TSPLObserver2());//$subject->detach($observer1);$subject->notify();exit();立即学习“PHP免费学习笔记(深入)”;
>php basic.php
The new state of subject
The new state of subject one
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号