代码如下所示:
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,'欢迎您进入管理后台
';
}else{
echo "你好,'$user' 你已经被添加到了用户列表
";
}
}
//这是继承父类的抽象方法
public function update(SplSubject $subject) {}
//显示个人年龄
public function showAge($name,$age){
echo "