4.3、php观察者实现
2018-07-14 本文已影响9人
水电梁师傅
SplSubject接口 和SplObserver接口
其中SplSubject为被观察者
SplObserver为观察者
//被观察者
class Login implements SplSubject
{
public $splobservers = null;
public $times = 0;
public function __construct()
{
$this->times = mt_rand(1, 9);
$this->splobservers = new SplObjectStorage();
}
public function attach(SplObserver $SplObserver)
{
$this->splobservers->attach($SplObserver);
}
public function detach(SplObserver $SplObserver)
{
$this->splobservers->detach($SplObserver);
}
public function notify()
{
foreach($this->splobservers as $v)
{
$v->update($this);
}
}
public function login()
{
$this->notify();
}
}
//观察者
class User implements SplObserver
{
public function update(SplSubject $splsubject)
{
echo '该用户登陆了'.$splsubject->times.'次';
}
}
$user = new User();
$login = new Login();
$login->attach($user);
$login->login();