php 权限 - 位运算符

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 权限 - 位运算符相关的知识,希望对你有一定的参考价值。

<?php


class Permissions {

	const ADD_CONTENT = 0x1;
	const ADD_OWN_CONTENT = 0x2;
	const EDIT_CONTENT = 0x4;
	const EDIT_OWN_CONTENT = 0x8;
	const DELETE_CONTENT = 0x10;
	const DELETE_OWN_CONTENT = 0x20;
	const ADD_COMMENT = 0x40;
	const VIEW_COMMENT = 0x80;

/*
	define("f0", 0x1); // 2^0
	define("f1", 0x2); // 2^1
	define("f2", 0x4); // 2^2
	define("f3", 0x8); // 2^3
	define("f4", 0x10); // 2^4
	define("f5", 0x20); // 2^5
	// ...
	define("f20", 0x1000000); // 2^20
	define("f21", 0x2000000); // 2^21
	define("f22", 0x4000000); // 2^22
	define("f23", 0x8000000); // 2^23
	define("f24", 0x10000000); // 2^24
	// ... up to 2^31
*/

}


function hasPermission($permissionToCheck, $userPermissions) {
		return $permissionToCheck & $userPermissions;
}

//Give the user some permissions
$myPermissions = Permissions::ADD_CONTENT | Permissions::EDIT_CONTENT | Permissions::VIEW_COMMENT;


//Can the user add content?
if (hasPermission(Permissions::ADD_CONTENT, $myPermissions)) echo 'User can add contnet';
else echo 'User cannot add content';

echo '<br />';

if (hasPermission(Permissions::EDIT_CONTENT, $myPermissions)) echo 'User can edit contnet';
else echo 'User cannot edit content';

echo '<br />';

if (hasPermission(Permissions::DELETE_CONTENT, $myPermissions)) echo 'User can delete contnet';
else echo 'User cannot delete content';


echo '<br />';

//Revoke a permission:
$myPermissions &= ~Permissions::ADD_CONTENT; 

//This should now be false
if (hasPermission(Permissions::ADD_CONTENT, $myPermissions)) echo 'User can add contnet';
else echo 'User cannot add content';

//Add a new permission:
$myPermissions |= Permissions::DELETE_OWN_CONTENT;

以上是关于php 权限 - 位运算符的主要内容,如果未能解决你的问题,请参考以下文章

php 位运算符的实际应用(权限判断)

关于PHP位运算的简单权限设计

php使用位与运算符&或|实现权限管理

php 的位运算总结

位运算经典算法

C#枚举中的位运算权限分配浅谈