Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> [PHP] Pierwsza Klasa
Grafnastyk
post
Post #1





Grupa: Zarejestrowani
Postów: 23
Pomógł: 0
Dołączył: 25.08.2017

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


Witam, czy mógłby mi ktoś wyjaśnić dlaczego moja funkcja use_monster zwraca tylko pierwszą zmienną? Domyślam się, że błąd jest banalny, ale nigdzie nie mogę znaleźć rozwiązania a błędu nie wyrzuca mi żadnego.

  1. <?php
  2.  
  3. class Monster
  4. {
  5. public
  6. $name,
  7. $hp,
  8. $def,
  9. $atk;
  10.  
  11. public function Create_monster($m_name, $m_hp, $m_def, $m_atk)
  12. {
  13. $this->name = $m_name;
  14. $this->hp = $m_hp;
  15. $this->def = $m_def;
  16. $this->atk = $m_atk;
  17.  
  18. }
  19.  
  20. public function use_monster()
  21. {
  22. return $this->name;
  23. return $this->hp;
  24. return $this->def;
  25. return $this->atk;
  26.  
  27.  
  28. }
  29.  
  30. }
  31.  
  32. $monster1 = new Monster;
  33.  
  34. $monster1->Create_monster('Troll',100,100,100);
  35.  
  36. echo $monster1->use_monster();
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
markuz
post
Post #2





Grupa: Zarejestrowani
Postów: 1 240
Pomógł: 278
Dołączył: 11.03.2008

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


  1. <?php
  2.  
  3. namespace Game;
  4.  
  5. class Monster
  6. {
  7. private $name;
  8. private $attack;
  9. private $defense;
  10. private $life;
  11.  
  12. public function __construct(string $name, int $attack, int $defense, int $life)
  13. {
  14. $this->name = $name;
  15. $this->attack = $attack;
  16. $this->defense = $defense;
  17. $this->life = $life;
  18. }
  19.  
  20. public function getName(): string
  21. {
  22. return $this->name;
  23. }
  24.  
  25. public function getAttack(): int
  26. {
  27. return $this->attack;
  28. }
  29.  
  30. public function getDefense(): int
  31. {
  32. return $this->defense;
  33. }
  34.  
  35. public function getLife(): int
  36. {
  37. return $this->life;
  38. }
  39. }


1. Obiekt tworzymy przez konstruktor a nie dodatkową metode.
2. Używamy normalnych nazw, bez żadnych skrótów które mogą wprowadzić w błąd.
3. Domyślnie każda właściwość powinna być prywatna

Ten post edytował markuz 10.12.2017, 13:05:08
Go to the top of the page
+Quote Post

Posty w temacie


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

 



RSS Aktualny czas: 9.10.2025 - 04:11