//被察者抽象类
class Observed implements SplSubject{
protected ¥_name;
protected ¥_observers;
//实例化,生成一个调查者对象
public function __construct(){
¥this->_observers = new SplObjectStorage();
}
// 添加调查者对象
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->showMessage(¥this);
}
}
//通俗办法: 设置值
public function setName(¥name){
¥this->_name = ¥name;
¥this->notify();
}
//通俗办法: 获取值
public function getName(){
return ¥this->_name;
}
//通俗办法:设置春秋
public function setAge(¥age){
¥this->age = ¥age;
foreach(¥this->_observers as ¥observer){
¥observer->showAge(¥this->_name,¥this->age);
}
}
}
// 调查者抽象类
class Observer implements SplObserver{
//显示消息提示
public function showMessage(SplSubject ¥obj){
¥user = ¥obj->getName();
if(¥user===admin){
echo 您好, ,¥user,迎接您进入经管后台<br/>;
}else{
echo 你好, ¥user 你已经被添加到了用户列表<br/>;
}
}
//这是持续父类的抽象办法
public function (SplSubject ¥subject) {}
//显示小我春秋
public function showAge(¥name,¥age){
echo <script>alert(¥name 的春秋是: ¥age)</script>;
}
}
¥subject = new Observed(); //生成一个被调查者对象
¥observer = new Observer(); //生成一个调查者对象
¥subject->attach(¥observer);//把调查者传入到被调查中去
¥subject->setName(张三); //调用 setName 办法
/
经由过程面的 setName 就会调用 ¥this->notify();
经由过程调用 ¥this->notify()就会调用 ¥observer->showMessage(¥this)办法,
即每个调查者对象的 showMessage(¥obj)办法;
/
¥subject->setName(admin);
¥subject->setAge(24);