Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP]Prosta gra na klasie, Singleton, sesja
mimol
post
Post #1





Grupa: Zarejestrowani
Postów: 247
Pomógł: 5
Dołączył: 10.12.2007

Ostrzeżenie: (0%)
-----


Witam. Napisałem sobie klasę game
  1. <?php
  2. class Game
  3. {
  4. private $number;
  5. private $try;
  6. private static $instance;
  7.  
  8. public static function getInstance()
  9. {
  10. if(self::$instance === null) {
  11. self::$instance = new Game();
  12. }
  13. return self::$instance;
  14. }
  15.  
  16. public function __construct()
  17. {
  18. $this->number = rand(1, 100);
  19. $this->try = 1;
  20. }
  21.  
  22. public function type($type)
  23. {
  24. if ($type == $this->number){
  25. echo 'Gratz. You need '.$this->try.' tries';
  26. } elseif ($type < $this->number){
  27. echo 'Select greater number';
  28. } else {
  29. echo 'Select smaller number';
  30. }
  31. $this->try++;
  32. }
  33. }
  34.  
  35. ?>

No i oczywiście plik z formularzem.
  1. <?php
  2. require 'game.php';
  3.  
  4. if (isset($_SESSION['game'])) {
  5. $game = unserialize($_SESSION['game']);
  6. } else {
  7. echo 'set';
  8. $game = Game::getInstance();
  9. $_SESSION['game'] = serialize($game);
  10. }
  11.  
  12. echo '<html><head><title>The Game</title></head><body>';
  13. echo '<form method="GET" enctype="text/plain">
  14. Number: <input type="text" name="number" pattern="\d*" />
  15. <input type="submit" />
  16. </form>';
  17.  
  18. if (isset($_GET['number'])) {
  19. $type = $_GET['number'];
  20. $game->type($type);
  21. }
  22.  
  23. ?>
  24. </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...
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 20.08.2025 - 18:59