Detailed code explanation of PHP's native support for the observer pattern

黄舟
Release: 2023-03-06 16:46:02
Original
1012 people have browsed it

Detailed code explanation of PHP’s native support forObserver pattern

storage = new SplObjectStorage(); } public function attach(SplObserver $obs) { $this->storage->attach($obs); } public function detach(SplObserver $obs) { $this->storage->detach($obs); } public function notify() { foreach($this->storage as $ol) { $ol->update($this); } } public function doAct() { echo 'DoAct ... 
'; $this->notify(); } } /** * concrete observer 1 */ class Observer1 implements SplObserver { public function update(SplSubject $sub) { echo 'Observer one updated!
'; } } /** * concrete observer 2 */ class Observer2 implements SplObserver { public function update(SplSubject $sub) { echo 'Observer two updated!
'; } } // test code $sub = new ConcreteSubject(); $sub->attach(new Observer1()); //add observer $sub->attach(new Observer1()); $sub->attach(new Observer2()); $sub->doAct();
Copy after login

The above is the detailed content of Detailed code explanation of PHP's native support for the observer pattern. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!