Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling PHP Bit Flags

I have a PHP class with a method that prints out an instance into a table row. Sometimes I want a row to be printed out without the name at the start, sometimes I want all the row items to be printed, and so on.

I have decided to use bit flags in order to make the code more readable, but the handling of the flags looks horrible. This is my first time using bit flags.

I have defined the flags at the top of the class as follows;

define('BAT_TABLE_ROW_PLAYER', 1);
define('BAT_TABLE_ROW_NOPLAYER', 2);
define('BAT_TABLE_ROW_FIELD', 4);
define('BAT_TABLE_ROW_ALL', 7);

The function that uses the flags looks like this;

function tableLine($flag=BAT_TABLE_ROW_ALL) {
    if(in_array($flag,[1,3,5,7]))
        // just return player cell
    if(in_array($flag,[2,3,6,7]))
        // return all other cells (except fielding)
    if(in_array($flag,[4,5,6,7]))
        // return fielding cells

    return $rtn;
}

So as you can see, if BAT_TABLE_ROW_ALL is set, all the options execute as planned.

The problem is, if I was to add another flag for some reason (therefore setting that to 8, and ALL to 15 - although that would be trivial as it stands), I would have to rewrite the entire function. This can't be right.

Is there a better way to write the function above so all I have to do is update the flag definitions, then just add the extra flag execution to the function?

like image 321
worldofjr Avatar asked Jun 22 '26 13:06

worldofjr


2 Answers

Bitwise operators

function tableLine($flag=BAT_TABLE_ROW_ALL) {
    if($flag & BAT_TABLE_ROW_PLAYER)
        // just return player cell
    if($flag & BAT_TABLE_ROW_NOPLAYER)
        // return all other cells (except fielding)
    if($flag & BAT_TABLE_ROW_FIELD)
        // return fielding cells

    return $rtn;
}

Also, you can avoid having to bump up the ALL flag constantly just:

define('BAT_TABLE_ROW_ALL', -1);

Which basically just has all bits set to 1.

like image 143
Sammitch Avatar answered Jun 25 '26 18:06

Sammitch


You should be using bitwise operators

It's difficult to understand exactly what your function is trying to do, but if you want to check whether a flag contains a certain bit, you can do the following

if($flag & BAT_TABLE_ROW_FIELD) {
    // Flag contains the field bit...
}
like image 38
Scopey Avatar answered Jun 25 '26 18:06

Scopey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!