php -s 用法,PHP SplEnum 用法 手册 | 示例代码

Source: https://stackoverflow.com/a/254543/508666

if class SplEnum is not present, I would normally use something simple like the following:

abstract class DaysOfWeek

{

const Sunday = 0;

const Monday = 1;

// etc.

}

$today = DaysOfWeek::Sunday;

However, other use cases may require more validation of constants and values.

abstract class BasicEnum {

private static $constCacheArray = NULL;

private function __construct(){

/*

Preventing instance :)

*/

}

private static function getConstants() {

if (self::$constCacheArray == NULL) {

self::$constCacheArray = [];

}

$calledClass = get_called_class();

if (!array_key_exists($calledClass, self::$constCacheArray)) {

$reflect = new ReflectionClass($calledClass);

self::$constCacheArray[$calledClass] = $reflect->getConstants();

}

return self::$constCacheArray[$calledClass];

}

public static function isValidName($name, $strict = false) {

$constants = self::getConstants();

if ($strict) {

return array_key_exists($name, $constants);

}

$keys = array_map('strtolower', array_keys($constants));

return in_array(strtolower($name), $keys);

}

public static function isValidValue($value) {

$values = array_values(self::getConstants());

return in_array($value, $values, $strict = true);

}

}

By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:

abstract class DaysOfWeek extends BasicEnum {

const Sunday = 0;

const Monday = 1;

const Tuesday = 2;

const Wednesday = 3;

const Thursday = 4;

const Friday = 5;

const Saturday = 6;

}

DaysOfWeek::isValidName('Humpday');                  // false

DaysOfWeek::isValidName('Monday');                   // true

DaysOfWeek::isValidName('monday');                   // true

DaysOfWeek::isValidName('monday', $strict = true);   // false

DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true

DaysOfWeek::isValidValue(5);                         // true

DaysOfWeek::isValidValue(7);                         // false

DaysOfWeek::isValidValue('Friday');                  // false

As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值