interface Observer
{
function notify($obj);
}
class ExchangeRate
{
static private $instance = NULL;
private $observers = array();
private $exchange_rate;
private function ExchangeRates()
{
}
static public function getInstance()
{
if (self::$instance == NULL)
{
self::$instance = new ExchangeRate();
}
return self::$instance;
}
public function getExchangeRate()
{
return $this->$exchange_rate;
}
public function setExchangeRate($new_rate)
{
$this->$exchange_rate = $new_rate;
$this->notifyObservers();
}
public function registerObserver($obj)
{
$this->observers[] = $obj;
}
function notifyObservers()
{
foreach($this->observers as $obj)
{
$obj->notify($this);
}
}
}
class ProductItem implements Observer
{
public function __construct()
{
ExchangeRate::getInstance()->registerObserver($this);
}
public function notify($obj)
{
if ($obj instanceof ExchangeRate)
{
// Update exchange rate data
print "Received update!\n";
}
}
}
$product1 = new ProductItem();
$product2 = new ProductItem();
$q = new ExchangeRate();
$q->setExchangeRate(4);
ExchangeRate::getInstance()->setExchangeRate(4);
пример из книжки. Должно выдавать 2 радостных сообщения "Received update!\n", а выдает
Fatal error: Cannot access empty property in Z:\home\localhost\www\newproject\observerclass.php on line 29 :(
собственно, ошибка в методе setExchangerate, но я не понимаю какая :)
строки
$q = new ExchangeRate();
$q->setExchangeRate(4);
закоментите, это мои эксперименты))