Category: Software Engineering

PHP Software Engineering

What is a bitmask?

Saw stuff like error_reporting(E_ERROR | E_WARNING | E_PARSE); or heard about bitmasks and got confused how it actually works? To my shame I never looked it up in like 12 years of programming until now.

What it actually is, is a quite efficient way to define for example grants for a user or which features are enabled for an application. It’s also quite old school but often seen and still in use.

At this point I’d suggest you to also open the PHP documentation where they explain all existing bitwise operators. I created some examples here to make it easier to understand and to visualise what is happening.

So what we’ve learned:

  • We have a 4 bits and we assign a meaning to each of them
  • We can individually switch single bits to express a state
  • Bitwise operations are supposed to be very fast and efficient
  • Use only numbers with a power of 2, otherwise we would mess up the bitmask because the binary system represent a number which is not of the power of 2 by two or more bits
  • Using a bitmask for a simple ACL system and putting each grant into a const might even make it readable and easy to work with

Would I use it? Maybe or maybe not it really depends on what I exactly need. It’s fast and solid when done right but will become messy when it’s getting much more complex. But in case you run into legacy code as I did this might help you to understand it.

Software Engineering

PHP proper string to boolean casts

Casting a string to a boolean can be tricky but it’s actually super easy. First of all never use boolval or casts like (bool) $string. It will never work or won’t result in what you believe it will. There are good reasons why it’s like that and I’m aware that other languages cope that with ease.

Just use filter_var which can properly convert strings into booleans. filter_var can do a lot more, but for booleans I use it all the time. Also check out if your framework provides something cool, some does, some doesn’t.

Just a common mistake I’ve often seen. Cheers and have fun coding!

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.