Last active
July 3, 2023 15:01
-
-
Save ziadoz/4710a96bd0dd3039da53c790aeac8877 to your computer and use it in GitHub Desktop.
PHP Enum Next/Previous Case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
enum Foo: string | |
{ | |
case A = 'A'; | |
case B = 'B'; | |
case C = 'C'; | |
public function next(): self | |
{ | |
if ($this === self::cases()[count(self::cases()) - 1]) { | |
return $this; | |
} | |
return self::cases()[array_search($this, self::cases()) + 1]; | |
} | |
public function prev(): self | |
{ | |
if ($this === self::cases()[0]) { | |
return $this; | |
} | |
return self::cases()[array_search($this, self::cases()) - 1]; | |
} | |
} | |
print_r(Foo::cases()); | |
print_r(array_search(Foo::C, Foo::cases(), true)); | |
print_r(Foo::A->next()->next()->next()); | |
print_r(Foo::C->prev()->prev()->prev()); | |
print_r(Foo::B->next()->prev()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment