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?