Created
August 23, 2018 20:17
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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