代碼如下所示:
復制代碼 代碼如下:
//被察者抽象類
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 update(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);