Created
September 14, 2011 07:38
-
-
Save boxers999/1216045 to your computer and use it in GitHub Desktop.
PHP SplObserver Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DemoSubject implements SplSubject{ | |
private $observer, $value; | |
public function __construct(){ | |
$this->observers = array(); | |
} | |
public function attach(SplObserver $observer){ | |
$this->observers[] = $observer; | |
} | |
public function detach(SplObserver $observer){ | |
if(($idx = array_search($observer, $this->observers, true)) !== false){ | |
unset($this->observers[$idx]); | |
} | |
} | |
public function notify(){ | |
foreach($this->observers as $observer){ | |
$observer->update($this); | |
} | |
} | |
public function setValue($value){ | |
$this->value = $value; | |
$this->notify(); | |
} | |
public function getValue(){ | |
return $this->value; | |
} | |
} | |
class DemoObserver implements SplObserver { | |
public function update(SplSubject $subject){ | |
echo 'This is the value :- '. $subject->getValue(); | |
} | |
} | |
$subject = new DemoSubject(); | |
$observer = new DemoObserver(); | |
$subject->attach($observer); | |
$subject->setValue(5); | |
$subject->detach($observer); | |
$subject->setValue(10); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 5 : private $observers, $value;