Witam. Napisałem sobie klasę game
<?php
class Game
{
private $number;
private $try;
public static function getInstance
() {
if(self::$instance === null) {
self::$instance = new Game();
}
return self::$instance;
}
public function __construct()
{
$this->number = rand(1
, 100
); $this->try = 1;
}
public function type($type)
{
if ($type == $this->number){
echo 'Gratz. You need '.$this->try.' tries'; } elseif ($type < $this->number){
echo 'Select greater number'; } else {
echo 'Select smaller number'; }
$this->try++;
}
}
?>
No i oczywiście plik z formularzem.
<?php
require 'game.php';
if (isset($_SESSION['game'])) { } else {
$game = Game::getInstance();
}
echo '<html><head><title>The Game</title></head><body>'; echo '<form method="GET" enctype="text/plain"> Number: <input type="text" name="number" pattern="\d*" />
<input type="submit" />
</form>';
if (isset($_GET['number'])) { $type = $_GET['number'];
$game->type($type);
}
?>
</body></html>
Moje pytanie brzmi, czy da to się łatwiej zrobić? (bez wykorzystywania sesji, raz ustawić obiekt i potem cały czas z niego korzystać) Po co używać wzorca singleton. Przecież podczas pisania kodu, osoba, która go pisze wie czy utworzyła już dany obiekt czy nie...