An extremely useful way of storing flags/values in PHP is to use bit operations which set the bits in a single integer value, which you can then test against. Often when a system grows, you need a flexible way of adding new flags with the minimum of impact. Using the method below, doing so is as easy as adding a new constant to your model and using it.
If we have the following constants defined in PHP (we usually store these in the model)
Then these are represented as bits like this
We can then go about setting the bits in variables, which we will later use to test against.
Using the bit map above, you can see why this happens.
If we take $iUser1 and do an ‘&’ with kListOne you get this
Doing an ‘&’ looks for bits that are set in both comparators and gives us 2 which is the value if kListOne, so we know they are subscribed to this.
I would be interested in knowing what other people use bit operators for, so feel free to comment below.
Leave a Reply