note 91291 added to language.operators.bitwise
| From: | grayda dot NOSPAM at DONTSPAM dot solidinc dot org | Date: | Thu, 04 Jun 2009 03:48:55 +0000 |
| Subject: | note 91291 added to language.operators.bitwise | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-156344@lists.php.net to get a copy of this message | ||
Initially, I found bitmasking to be a confusing concept and found no use for it. So I've
whipped up this code snippet in case anyone else is confused:
<?php
// The various details a vehicle can have
$hasFourWheels = 1;
$hasTwoWheels = 2;
$hasDoors = 4;
$hasRedColour = 8;
$bike = $hasTwoWheels;
$golfBuggy = $hasFourWheels;
$ford = $hasFourWheels | $hasDoors;
$ferrari = $hasFourWheels | $hasDoors | $hasRedColour;
$isBike = $hasFourWheels & $bike; # False, because $bike doens't have four
wheels
$isGolfBuggy = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels
$isFord = $hasFourWheels & $ford; # True, because $ford $hasFourWheels
?>
And you can apply this to a lot of things, for example, security:
<?php
// Security permissions:
$writePost = 1;
$readPost = 2;
$deletePost = 4;
$addUser = 8;
$deleteUser = 16;
// User groups:
$administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser;
$moderator = $readPost | $deletePost | $deleteUser;
$writer = $writePost | $readPost;
$guest = $readPost;
// function to check for permission
function checkPermission($user, $permission) {
if($user & $permission) {
return true;
} else {
return false;
}
}
// Now we apply all of this!
if(checkPermission($administrator, $deleteUser)) {
deleteUser("Some User"); # This is executed because $administrator can $deleteUser
}
?>
Once you get your head around it, it's VERY useful! Just remember to raise each value by the
power of two to avoid problems
----
Server IP: 117.55.229.1
Probable Submitter: 203.206.183.72
----
Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php
Edit -- https://master.php.net/note/edit/91291
Del: integrated -- https://master.php.net/note/delete/91291/integrated
Del: useless -- https://master.php.net/note/delete/91291/useless
Del: bad code -- https://master.php.net/note/delete/91291/bad+code
Del: spam -- https://master.php.net/note/delete/91291/spam
Del: non-english -- https://master.php.net/note/delete/91291/non-english
Del: in docs -- https://master.php.net/note/delete/91291/in+docs
Del: other reasons-- https://master.php.net/note/delete/91291
Reject -- https://master.php.net/note/reject/91291
Search -- https://master.php.net/manage/user-notes.php