PHP 5 + standard function library observer implementation _ PHP Tutorial

Source: Internet
Author: User
PHP 5 + standard function library observer implementation. PHP 5 + standard function library observer implementation PHP Observer design mode implementation is relatively simple, but PHP5 version already supports standard library Library, we only need to simply inherit and implement the 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

The Observer design mode of ghost PHP is relatively simple to implement, but the PHP 5 version already has support for standard library libraries. we only need to simply inherit and implement it...

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.