The code looks like this:
Copy CodeThe code is as follows:
Abstract class of the person being observed
Class observed implements splsubject{
protected $_name;
protected $_observers;
Instantiate, generate an observer object
Public Function __construct () {
$this->_observers = new Splobjectstorage ();
}
Add Observer Object
Public function Attach (Splobserver $observer) {
$this->_observers->attach ($observer);
}
Delete Viewer Object
Public Function Detach (Splobserver $observer) {
$this->_observers->detach ($observer);
}
Notification message
Public Function notify () {
foreach ($this->_observers as $observer) {
$observer->showmessage ($this);
}
}
Common methods: Setting values
Public Function SetName ($name) {
$this->_name = $name;
$this->notify ();
}
Common method: Get 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 prompt
Public Function ShowMessage (Splsubject $obj) {
$user = $obj->getname ();
if ($user = = = ' Admin ') {
echo ' Hello, ', $user, ' welcome you to the management background
';
}else{
echo "Hello, ' $user ' you have been added to the user list
";
}
}
This is an abstract method that inherits the parent class
Public Function Update (Splsubject $subject) {}
Show your Age
Public Function Showage ($name, $age) {
echo "";
}
}
$subject = new observed (); Generate an object to be observed by
$observer = new Observer (); Generate an Observer object
$subject->attach ($observer);//pass the observer to the observed
$subject->setname (' Zhang San '); Calling the SetName method
/*
* $this->notify () will be called through the setName of the polygon;
* $observer->showmessage ($this) method is called by calling $this->notify ().
* The ShowMessage ($obj) method for each observer object;
*/
$subject->setname (' admin ');
$subject->setage (24);
http://www.bkjia.com/PHPjc/326995.html www.bkjia.com true http://www.bkjia.com/PHPjc/326995.html techarticle The code looks like this: the copy code code is as follows://The Reviewer abstract class observed implements splsubject{protected $_name; protected $_observers;//instantiation, creating a view The Observer ...