Skip to content

Instantly share code, notes, and snippets.

@5SMNOONMS5
Last active August 13, 2018 02:58
Show Gist options
  • Save 5SMNOONMS5/f54d93e323ab0cdffd6a6de5e36fc91b to your computer and use it in GitHub Desktop.
Save 5SMNOONMS5/f54d93e323ab0cdffd6a6de5e36fc91b to your computer and use it in GitHub Desktop.
通過 bitwise 方式來判斷權限
<?php
$premissionA = 1; // 1
$premissionB = 1 << 1; // 2
$premissionC = 1 << 2; // 4
$premissionD = 1 << 3; // 8
$premissionE = 1 << 4; // 16
$premissionF = 1 << 5; // 32
$premissionG = 1 << 6; // 64
$premissionH = 1 << 7; // 128
$premissionI = 1 << 8; // 256
$premissionJ = 1 << 9; // 512
// Users 直接用 OR 的方式來 chain 權限,或者直接給數字
$administrator = $premissionA | $premissionB | $premissionC | $premissionD | $premissionJ;
$developer = 100;
// developer 只有 premissionH + premissionG + premissionD
// 01100100 = 100
// ★★★★★★★★★★★★ 這樣會錯 ★★★★★★★★★★★★ 不能用加號
$moderator = $premissionA + $premissionB + $premissionC + $premissionD;
// function to check for permission
function checkPermission($user, $permission) { return ($user & $permission); }
function deletePermission($user, $permission) { if (checkPermission($user, $premissionJ)) { return ($user ^ $permission); }}
echo
(checkPermission($administrator, $premissionJ)
? "have premissionJ" /// 有 J
: "do not have premissionJ");
echo
(checkPermission($developer, $premissionB)
? "do have premissionB"
: "do not have premissionB"); /// 沒有 B
echo
(checkPermission($developer, $premissionH)
? "do have premissionH" /// 有 H
: "do not have premissionH");
echo
(deletePermission($developer, $premissionH)
? "do have premissionH"
: "do not have premissionH"); /// 沒有 H
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment