我正在尝试使用按位操作在PHP中创建“枚举”类。
class PermissionBitmap {
const VIEW = 1;
//if you can EDIT, you can VIEW
const EDIT = 2 | self::VIEW;
//if you can CREATE, you can VIEW
const CREATE = 4 | self::VIEW;
//if you can DELETE you can VIEW
const DELETE = 8 | self::VIEW;
//if you are ADMIN you can VIEW, EDIT, CREATE and DELETE
const ADMIN = self::EDIT | self::CREATE | self::DELETE;
//function to check if $permisison1 is contain within $permision2
// perm_contains(self::VIEW, self::CREATE); //should return true.
// perm_contains(self::DELETE, self::ADMIN); //should return true.
// perm_contains(self::CREATE, self::EDIT); //should return false.
public static function perm_contains($permisison1, $permisison2): bool {
return ($permisison1 & $permisison2) === $permisison1;
}
}
var_dump(PermisisonBitmap::EDIT); //sums to 3... all correct bits are set
var_dump(PermissionBitmap::ADMIN); //sums to 15... all correct bits are set
因此,我将“枚举”设置为级联,以便特定的权限包含在较高的权限中。 (例如,VIEW应该包含在EDIT,CREATE和DELETE中。所有内容都应包含在ADMIN中)。我认为使用按位或(|)是正确的方法,并且似乎会产生正确的结果。
如果有一个权限包含在另一个权限中,那么我遇到的问题就是如何进行测试。我目前所拥有的是($permisison1 & $permisison2) === $permisison1;
,但我对它的普遍正确性表示怀疑。
在所有情况下(例如,如果我向枚举添加更复杂的权限),这是否正确?还是有一种更好/更正确的方法?