The code looks like this:
Copy Code code as follows:
The abstract class of the person being observed
Class observed implements splsubject{
protected $_name;
protected $_observers;
Instantiated to generate an observer object
Public Function __construct () {
$this->_observers = new Splobjectstorage ();
}
Add Observer Object
Public function Attach (Splobserver $observer) {
$this->_observers->attach ($observer);
}
Delete a Viewer object
Public Function Detach (Splobserver $observer) {
$this->_observers->detach ($observer);
}
Notification message
Public Function notify () {
foreach ($this->_observers as $observer) {
$observer->showmessage ($this);
}
}
Normal method: Setting a value
Public Function SetName ($name) {
$this->_name = $name;
$this->notify ();
}
Normal method: Get the value
Public Function GetName () {
return $this->_name;
}
Common method: Set age
Public Function Setage ($age) {
$this->age = $age;
foreach ($this->_observers as $observer) {
$observer->showage ($this->_name, $this->age);
}
}
}
Observer abstract class
Class Observer implements splobserver{
Show Message Hints
Public Function ShowMessage (Splsubject $obj) {
$user = $obj->getname ();
if ($user = = ' admin ') {
echo ' Hello, ', $user, ' welcome you into admin <br/> ';
}else{
echo "Hello, ' $user ' you have been added to the user list <br/>";
}
}
This is an abstract method that inherits the parent class
Public Function Update (Splsubject $subject) {}
Show personal Age
Public Function Showage ($name, $age) {
echo "<script>alert (' $name Age: $age ') </script>";
}
}
$subject = new observed (); To generate a observed object
$observer = new Observer (); Generate an Observer object
$subject->attach ($observer);//pass the observer to the observed
$subject->setname (' John '); Calling the SetName method
/*
* $this->notify () will be invoked through the setname of the surface;
* $observer->showmessage ($this) method is invoked by calling $this->notify ().
* i.e. the ShowMessage ($obj) method of each observer object;
*/
$subject->setname (' admin ');
$subject->setage (24);