Skip to content

Instantly share code, notes, and snippets.

@imliam imliam/example.php
Created Aug 23, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.