ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 实例 ``` class User implements splsubject{ /** * 观察者列表 * @var SplObjectStorage */ protected $observer; public function __construct() { $this->observer = new SplObjectStorage(); } public function login() { $this->notify(); echo 'login complete \n'; } public function success(){ echo "success\n"; } public function attach(SplObserver $observer) { $this->observer->attach($observer); } public function detach(SplObserver $observer) { $this->observer->detach($observer); } public function notify() { $this->observer->rewind(); while ($this->observer->valid()) { $observer = $this->observer->current(); $observer->update($this); $this->observer->next(); } } } class Cat implements SplObserver{ public function update(SplSubject $subject) { $subject->success(); } } class Dog implements SplObserver{ public function update(SplSubject $subject) { $subject->success(); } } $cat = new Cat(); $dog = new Dog(); $user = new User(); $user->attach($cat); $user->attach($dog); $user->login(); ```