3

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?

worldofjr
  • 3,868
  • 8
  • 37
  • 49

2 Answers2

7

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.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • I see. So `&` basically works like a mask of the given flag definition over `$flag`. It's amazing the other google results you can get once you know the right search term! – worldofjr Oct 08 '14 at 00:54
2

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...
}
Scopey
  • 6,269
  • 1
  • 22
  • 34