标签:highlight user lob observer 观察者 this undo subject 次数
/** * 观察对象 * Undocumented class */ class User implements SplSubject { public $loginCnt; private $observers; public function __construct() { $this->observers = new SplObjectStorage; } public function login() { $this->loginCnt = rand(1,30); $this->notify(); } public function attach(SplObserver $observer) { $this->observers->attach($observer); } public function detach(SplObserver $observer) { $this->observers->detach($observer); } public function notify() { foreach($this->observers as $observer) { $observer->update($this); } } } /** * 观察者 * Undocumented class */ class Security implements SplObserver { public function update(SplSubject $subject) { if ($subject->loginCnt > 10) { echo ‘登录次数过多‘; } else { echo ‘登录正常‘; } } } $user = new User(); $user->attach(new Security()); $user->login();
标签:highlight user lob observer 观察者 this undo subject 次数
原文地址:https://www.cnblogs.com/xiangdongsheng/p/13363852.html