I'm not sure if bitmask is the correct term. Let me explain:
In php, the error_reporting
function can be called multiple ways:
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
I got the term bitmask from the php.net page here
Anyway the point of this is, I have implemented a SIMPLE method called ls
which returns the contents of a directory.
This function takes 3 args... ( $include_hidden = false, $return_absolute = false, $ext = false )
So when i call the function, i set how i want the results. Whether i want the results to return hidden directories, whether i want basenames only etc.
so when i call the function i'm writing
ls(true, false, true)
ls(false, false, true)
ls(true, true, true)
etc...
I thought it would be much more readable if i could just flag how i want the data returned?
so something like:
ls( INCLUDE_HIDDEN | HIDE_EXTS );
ls( SHOW_ABSOLUTE_PATHS | HIDE_EXTS );
etc...
How would i implement this in terms of testing which flags have been called?
The others have offered good suggestions, but these days it's much more common to pass in associative arrays instead of bitmasks. It's much more readable and allows you to pass in other variables other than just true/false values. Something like this:
You can then check for individual flags in your
ls
function:It's quite simple actually. First a bit of code to demonstrate how it can be implemented. If you don't understand anything about what this code is doing or how it works, feel free to ask additional questions in the comments:
Demo
Because the flags are integers, on a 32-bit platform you define up to 32 flags. On a 64-bit platform, it's 64. It is also possible to define the flags as strings, in which case the number of available flags is more or less infinite (within the bounds of system resources, of course). Here's how it works in binary (cut down to 8-bit integers for simplicity).
When you combine the flags to pass them to the function, you OR them together. Let's take a look at what happens when we pass
FLAG_1 | FLAG_3
And when you want to see which flags were set, you AND the bitmask with the flag. So, lets take the result above and see if
FLAG_3
was set:...we get the value of the flag back, a non-zero integer - but if we see if
FLAG_2
was set:...we get zero. This means that you can simply evaluate the result of the AND operation as a boolean when checking if the value was passed.