Skip to content

Instantly share code, notes, and snippets.

@leihog
Created September 14, 2010 11:41
Show Gist options
  • Save leihog/578905 to your computer and use it in GitHub Desktop.
Save leihog/578905 to your computer and use it in GitHub Desktop.
<?php
define('FLAG_0', 1);
define('FLAG_1', 2);
define('FLAG_2', 4);
define('FLAG_3', 8);
/**
* Will fail when setting multiple flags at once
*/
function setFlag($flag)
{
global $flags;
if (($flags & $flag))
{
return;
}
$flags |= $flag;
}
/**
* Proper way to do it
*/
function setFlag2($flag)
{
global $flags;
if (($flags & $flag) == $flag)
{
return;
}
$flags |= $flag;
}
function removeFlag($flag)
{
global $flags;
$flags ^= $flag;
}
function removeFlag2($flag)
{
global $flags;
$flags &= ~$flag;
}
/**
* This fails on multiple flags
*/
function removeFlag3($flag)
{
global $flags;
if (($flags & $flag) == $flag)
{
$flags &= ~$flag;
}
}
/**
* This works as intended
*/
function removeFlag4($flag)
{
global $flags;
if ($flags & $flag)
{
$flags &= ~$flag;
}
}
echo "setting flags \n";
echo "Test 1: setFlag(FLAG_2); start: 0, expecting: 4 \n";
$flags = 0;
setFlag(FLAG_2);
echo "value is $flags \n\n";
echo "Test 2: setFlag(FLAG_1 | FLAG_2); start: 4, expecting: 6 \n";
setFlag(FLAG_1 | FLAG_2);
echo "Value is $flags \n\n";
echo "Test 3: setFlag2(FLAG_1 | FLAG_2); start: 4, expecting: 6 \n";
$flags = 4;
setFlag2(FLAG_1 | FLAG_2);
echo "value is $flags \n\n";
echo "Removing flags \n";
echo "Test 4: removeFlag(FLAG_3); start: 6, expecting: 6 \n";
removeFlag(FLAG_3);
echo "value is $flags \n\n";
echo "test 5: removeFlag2(FLAG_3); start: 6, expecting: 6 \n";
$flags = 6;
removeFlag2(FLAG_3);
echo "value is $flags \n\n";
echo "Test 6: removeFlag3(FLAG_3 | FLAG_2); start: 6, expecting: 2 \n";
removeFlag3(FLAG_3 | FLAG_2);
echo "value is $flags \n\n";
echo "Test 7: removeFlag4(FLAG_3 | FLAG_2); start: 6, expecting: 2 \n";
removeFlag4(FLAG_3 | FLAG_2);
echo "value is $flags \n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment