Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: max(five, six)?
(Example: nine)

The Note You're Voting On

grayda dot NOSPAM at DONTSPAM dot solidinc dot org
16 years ago
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

<< Back to user notes page

To Top