<?php
class Game {
public $name;
public $listeners = array();
public function __construct($name) {
$this->name = $name;
}
function addListener($listener) {
$this->listeners[] = $listener;
}
function start() {
foreach ($this->listeners as $listener) {
$listener->gameStarted($this->name);
}
}
}
class Statistic {
public $startsCount = 0;
public $lastGame = "";
function gameStarted($name) {
$this->startsCount++;
$this->lastGame = $name;
}
}
$statistic = new Statistic();
$heroes = new Game("Heroes");
$doom = new Game("Doom");
//subscribe to events
$heroes->addListener($statistic);
$doom->addListener($statistic);
$doom->start();
$heroes->start();
//statistic.lastGame is "Heroes"
//statistic.startsCount is 2
echo $statistic->lastGame, "\n";
echo $statistic->startsCount;