2

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.

NewProger
  • 2,945
  • 9
  • 40
  • 58
  • possible duplicate of [pass multiple defines or const as a parameter to a class method](http://stackoverflow.com/questions/9644085/pass-multiple-defines-or-const-as-a-parameter-to-a-class-method) – Brad Mar 23 '12 at 14:36
  • Check http://www.shawnolson.net/a/601/setting_bits_and_flags_in_php.html – N.B. Mar 23 '12 at 14:43

2 Answers2

2

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.

NewProger
  • 2,945
  • 9
  • 40
  • 58
1

You might want to use an array for your $flags argument, like so:

function flagtest($flags = false)
{
    if (is_array($flags)
    {
        foreach ($flags as $index => $value)
        {
            if ($value == true) echo "flag $index is on\n";
        } 
    }
}

$my_flags = array(true, true, false);
flagtest($my_flags); // -> flag1 is on, flag2 is on, 
vzwick
  • 11,008
  • 5
  • 43
  • 63