设置二进制权限 [英] Set permissions in binary

查看:204
本文介绍了设置二进制权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学校看到一个使用二进制字符串设置权限的系统.

I saw in school a system that set permissions using binary string.

比方说101001 = 41

Let's say 101001 = 41

所以:

  • 1可以访问第1页
  • 2可以访问第2页
  • 4可以访问第3页
  • 可以授予第8页的权限
  • 16位可以访问第5页
  • 可以授予第6页的权限

所以说我得到了上面的二进制字符串(101001).我可以访问第1、4和6页.

So let's say I got the above binary string (101001). I have access to page 1, 4 and 6.

如何在PHP中执行此操作?假设我在MySQL中有一个名为perms的字段存储在dec中,所以101001将是41.我怎么知道PHP中41等于1、8和32?

How can I do this in PHP ? Let's say I got a field in MySQL named perms stored in dec so 101001 will be 41. How can I know that 41 is equal to 1, 8 and 32 in PHP ?

谢谢.

推荐答案

听起来像您在谈论位和按位运算符.设置此权限最简单的方法是为每个权限定义常量

Sounds like you're talking about bits and bit-wise operators. This easiest way to set this up is to define constants for every permission

const POST   = 1;
const DELETE = 2;
const UPDATE = 4;
const READ   = 8;

一旦定义了这些,就很容易使用按位运算符进行比较:

Once you have these defined it's easy to make comparisons using the bitwise operators:

$userValue = '1101';

if ($userValue & self::POST) {
  echo 'Can Post';
}

if ($userValue & self::DELETE) {
  echo 'Can Delete';
}

if ($userValue & self::UPDATE) {
  echo 'Can Update';
}

if ($userValue & self::READ) {
  echo 'Can Read';
}

这是PHP自身常量的工作量.如果您曾经使用E_ALL & E_DEPRECATED之类的方法设置错误报告,则实际上是在使用二进制数.

This is how many of PHP's own constants work. If you've ever set the error reporting using something like E_ALL & E_DEPRECATED you're actually working with binary numbers.

这篇关于设置二进制权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆