Search code examples
phpbit-manipulationbitflags

Binary flags for functions in php


Good day everyone.

I'm trying to figure out a way to use multiple flags for a function, without increasing number of arguments.

For example to use it like that some_func(flag1|flag2|flag3);

For now I did it like that

define('flag1', 1);
define('flag2', 2);
define('flag3', 4);

function flagtest($flags)
{
if ($flags & flag1)
    echo 'flag1 is on, '; 
if ($flags & flag2)
    echo 'flag2 is on, '; 
if ($flags & flag3)
    echo 'flag3 is on, '; 
}
flagtest(flag2 | flag3);

And it prings that flags 2 and 3 are on.

So, everything is working. But... I'm sure there's a better way to do it... Is that right? So, the question - how can I make it better? I'm sure there's a proper way to implement stuff like that.


Solution

  • Apparently it is the way it should be done. There's no need to do it any other way if the desired outcome is as described.