Created
March 22, 2021 04:45
-
-
Save showsky/c6372957b3fd46e32da14c63b183b277 to your computer and use it in GitHub Desktop.
PHP Enum Demo
This file contains hidden or 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 | |
abstract class BaseEnum | |
{ | |
public static function toArray() | |
{ | |
$reflection = new \ReflectionClass(static::class); | |
$constant = $reflection->getConstants(); | |
return $constant; | |
} | |
public static function __callStatic($name, $arguments) | |
{ | |
$arr = static::toArray(); | |
if(isset($arr[$name])){ | |
return $arr[$name]; | |
} | |
throw new \BadMethodCallException("找不到對應的列舉值 {$name}"); | |
} | |
} |
This file contains hidden or 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 | |
$userModel = new UserModel(); | |
$userModel->selectUser(UserTypeEnum::FACEBOOK()); | |
$userModel->selectUser(UserTypeEnum::GOOGLE()); | |
$userModel->selectUser(UserTypeEnum::LINE()); |
This file contains hidden or 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 | |
class UserModel | |
{ | |
public function selectUser(UserTypeEnum $loginType) { | |
//TODO: something ~ | |
} | |
} |
This file contains hidden or 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
class UserTypeEnum extends BaseEnum | |
{ | |
const GOOGLE = 1; | |
const FACEBOOK = 2; | |
const LINE = 3; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment