You are on page 1of 2

<?

php
class Memento {
private $state;
public function __construct($state) {
$this->state = $state;
}
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
}
class Originator {
private $state;
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
public function saveToMemento() {
return new Memento($this->state);
}
public function getStateFromMemento($memento) {
$this->state = $memento->getState();
}
}
class CareTaker {
private $mementoList = array();
public function add(Memento $state) {
$this->mementoList[] = $state;
}
public function get($index) {
return $this->mementoList[$index];
}
}
$originator = new Originator();
$careTaker = new CareTaker();
$originator->setState("state 1");
$originator->setState("state 2");
$careTaker->add($originator->saveToMemento());
$originator->setState("state 3");
$careTaker->add($originator->saveToMemento());
$originator->setState("state 4");
echo 'current state:'.$originator->getState();

$originator->getStateFromMemento($careTaker->get(0));
echo 'first saved state:'.$originator->getState();
$originator->getStateFromMemento($careTaker->get(1));
echo 'second saved state:'.$originator->getState();

You might also like