Skip to content

Instantly share code, notes, and snippets.

@imliam
Created August 23, 2018 20:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imliam/b740732b72fdb80685b540e9f021860d to your computer and use it in GitHub Desktop.
Save imliam/b740732b72fdb80685b540e9f021860d to your computer and use it in GitHub Desktop.
Define a set of constants to be used as flags for bitmasked options.
<?php
set_bitmask_flags([
'FLAG_1',
'FLAG_2',
'FLAG_3',
'FLAG_4',
'FLAG_5',
]);
function example_flags($flags)
{
if ($flags & FLAG_1) {
echo "You passed flag 1!" . PHP_EOL;
}
if ($flags & FLAG_2) {
echo "You passed flag 2!" . PHP_EOL;
}
if ($flags & FLAG_3) {
echo "You passed flag 3!" . PHP_EOL;
}
if ($flags & FLAG_4) {
echo "You passed flag 4!" . PHP_EOL;
}
if ($flags & FLAG_5) {
echo "You passed flag 5!" . PHP_EOL;
}
}
example_flags(FLAG_1 | FLAG_3 | FLAG_5);
// 'You passed flag 1!'
// 'You passed flag 3!'
// 'You passed flag 5!'
<?php
if (! function_exists('set_bitmask_flags')) {
/**
* Define a set of constants to be used as flags for bitmasked options.
*
* @param string[] $flags
* @return void
* @throws \InvalidArgumentException
*/
function set_bitmask_flags(array $flags): void
{
$flags = array_values($flags);
$index = 0;
foreach ($flags as $flag) {
$suffixZeroes = str_repeat('0', $index);
$binary = "0b1{$suffixZeroes}";
define($flag, bindec($binary));
$index++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment