Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Enumerator w PHP
batman
post
Post #1





Grupa: Moderatorzy
Postów: 2 921
Pomógł: 269
Dołączył: 11.08.2005
Skąd: 127.0.0.1




Oddaję dzisiaj pod waszą ocenę klasę enumeratora, którego tak bardzo mi brakuje w PHP (SplEnum to jakieś nieporozumienie). Jak sama nazwa wskazuje jet to standardowy typ wyliczeniowy, zaimplementowany w PHP.

Kod klasy
  1. namespace Batman;
  2.  
  3. abstract class Enum
  4. {
  5. private static $_consts = null;
  6.  
  7. final public function __construct()
  8. {
  9. throw new \ErrorException('Can\'t create object from enum');
  10. }
  11.  
  12. final static private function getConstants()
  13. {
  14. if(self::$_consts === null) {
  15. $class = get_called_class();
  16. if($class == __CLASS__) {
  17. throw new \BadMethodCallException('You can\'t access constants from Enum class');
  18. }
  19. $reflection = new \ReflectionClass($class);
  20. self::$_consts = $reflection->getConstants();
  21. }
  22. return self::$_consts;
  23. }
  24.  
  25. final static public function getNames()
  26. {
  27. return array_keys(self::getConstants());
  28. }
  29.  
  30. final static public function getValues()
  31. {
  32. return array_values(self::getConstants());
  33. }
  34. }


Przykład użycia
  1. class UserStatus extends \Batman\Enum
  2. {
  3. const DELETED = -1;
  4. const BLOCKED = 0;
  5. const ACTIVE = 1;
  6. }


Download, issue tracker i całą resztę znajdziecie na githubie.
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
Bags_Bunny
post
Post #2





Grupa: Zarejestrowani
Postów: 262
Pomógł: 39
Dołączył: 12.04.2004

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


  1. class EnumTest1 extends \Batman\Enum
  2. {
  3. const foo = 1;
  4. }
  5.  
  6. class EnumTest2 extends \Batman\Enum
  7. {
  8. const bar = 1;
  9. }
  10.  
  11. print_r( EnumTest1::getNames() ); //foo
  12. print_r( EnumTest2::getNames() ); //foo (!)
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: 18.10.2025 - 10:59