Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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, 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top