PHP 5 + standard function library observer implementation

Source: Internet
Author: User

PHP 5 + standard function library observer implementation

The observer design mode of PHP is relatively simple to implement, but the PHP5 + version already has support for standard library libraries. We only need to simply inherit and implement it.

Observer: implements the standard interface class library SplSubject. One registration method is attach and the other is detach. One notification method: nofity.

 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; }}

Observer: implements the standard interface class library SplObserver. An update method.

 getValue(); }}
 getValue(); }}


Test Call (in the same directory ):

 attach(new TSPLObserver());$observer1 = new TSPLObserver1();$subject->attach($observer1);//$subject->attach(new TSPLObserver2());//$subject->detach($observer1);$subject->notify();exit();

Output:

> Php basic. php
The new state of subject

The new state of subject one

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.