PHP枚举类
<?php
namespace Common\Enum;
class RoleEnum
{
const HOST = 0;
const MEMBER = 1;
const FRIEND = 2;
const RENT = 3;
const OTHER = 4;
public static $dataMap = [
self::HOST => "业主",
self::MEMBER => "成员",
self::FRIEND => "亲朋",
self::RENT => "租客",
self::OTHER => "其他"
];
public static function getName($id)
{
return self::$dataMap[$id];
}
public static function getIdName() {
$response = [];
foreach (self::$dataMap as $k => $v) {
$response[] = [
'id' => $k,
'name' => $v
];
}
return $response;
}
}
升级
<?php
namespace Common\Enum;
class RoleEnum extends CommonEnum
{
const HOST = 0;
const MEMBER = 1;
const FRIEND = 2;
const RENT = 3;
const OTHER = 4;
public static $dataMap = [
self::HOST => "业主",
self::MEMBER => "成员",
self::FRIEND => "亲朋",
self::RENT => "租客",
self::OTHER => "其他"
];
}
<?php
namespace Common\Enum;
/**
* 关于后期静态绑定主要说static::
* “后期绑定”的意思是说,static:: 不再被解析为定义当前方法所在的类,而是在实际运行时计算的。
* 说的简单点,就是 static:: 不会进行php代码检查,你可以调用一个类或者其父类中都没有的一个静态属性或方法,php不会报错;
* 只要在你写的代码在运行到 static:: 时这个类中有对应的属性或方法就行。
*/
abstract class CommonEnum
{
/**
* 获取名称
* @param $id
* @return mixed
*/
public static function getName($id)
{
// 这里用static 可以调用子类的属性,用self会报错
return static::$dataMap[$id];
}
/**
* 获取数组
* @return array
*/
public static function getIdName() {
$response = [];
// 这里用static 可以调用子类的属性,用self会报错
foreach (static::$dataMap as $k => $v) {
$response[] = [
'id' => $k,
'name' => $v
];
}
return $response;
}
/**
* 获取Id数组
* @return array
*/
public static function getIdArr($except = []) {
$response = [];
// 这里用static 可以调用子类的属性,用self会报错
foreach (static::$dataMap as $k => $v) {
if (!in_array($k, $except)) {
$response[] = $k;
}
}
return $response;
}
/**
* 检查是否在其中
* @param $id
* @param array $except
* @return bool
*/
public static function checkIn($id,$except = []) {
$response = [];
// 这里用static 可以调用子类的属性,用self会报错
foreach (static::$dataMap as $k => $v) {
if (!in_array($k, $except)) {
$response[] = $k;
}
}
return in_array($id,$response);
}
}