Skip to content

Instantly share code, notes, and snippets.

@showsky
Created March 22, 2021 04:45
Show Gist options
  • Save showsky/c6372957b3fd46e32da14c63b183b277 to your computer and use it in GitHub Desktop.
Save showsky/c6372957b3fd46e32da14c63b183b277 to your computer and use it in GitHub Desktop.
PHP Enum Demo
<?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}");
}
}
<?php
$userModel = new UserModel();
$userModel->selectUser(UserTypeEnum::FACEBOOK());
$userModel->selectUser(UserTypeEnum::GOOGLE());
$userModel->selectUser(UserTypeEnum::LINE());
<?php
class UserModel
{
public function selectUser(UserTypeEnum $loginType) {
//TODO: something ~
}
}
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