Ayad Mfs
Ayad Mfs

Reputation: 33

bitwise operators

I would like to understand the following code from Zenphoto’s plugin:

$plugin_is_filter = 5|ADMIN_PLUGIN|THEME_PLUGIN;

The snippet was disjointed from context. It is just about the Idea behind it.

Are 5|ADMIN_PLUGIN|THEME_PLUGIN Permissions using bitwise?

When it is useful to use?

Thanks for any hint, links.

Upvotes: 0

Views: 237

Answers (3)

Rex Redi
Rex Redi

Reputation: 93

The variable $plugin_is_filter is being used to flag which plugins to load. Essentially, it is being treated like an array bits that correspond to an enumerated set plugins. For more information, see the links below.

This explains what ADMIN_PLUGIN and THEME_PLUGIN are.

Search the page for '$plugin_is_filter' to get a brief explanation of how to use this variable.

http://www.zenphoto.org/news/zenphoto-plugin-architecture

I hope this helps.

Upvotes: 0

user229044
user229044

Reputation: 239230

Yes, that is an example of bitwise OR.

You typically use bitwise operations when you're interested in packing multiple boolean flags into a single integer. Bitwise operators allow you to manipulate the individual bits of a byte, meaning an 8 bit byte can be used to store 8 distinct boolean values. It's a technique which was useful when using a whole 8 bit byte to store a single binary "yes" or "no" was considered wasteful.

Today, there is virtually no reason to ever prefer using this kind of bitpacking in PHP (especially with a magic number like that 5) over a simple configuration array. It is a technique which adds virtually nothing of value to PHP code, increasing complexity and decreasing maintainability for no real gain. I would be very skeptical of any new PHP code produced which makes use of bitwise flags in this way.

Upvotes: 1

Waleed Khan
Waleed Khan

Reputation: 11467

Bitfields are useful when you need to provide a set of boolean options in one variable. For example, PHP lets you set your error reporting like this:

error_reporting(E_ERROR | E_WARNING | E_PARSE);

In binary, those constants have these values:

E_ERROR   0001
E_WARNING 0010
E_PARSE   0100

If you OR a set of options like that together, you'll be able to express the settings in one field:

E_ERROR | E_WARNING | E_PARSE 0111

Then, you can check for an option being set using AND:

if ($option & E_ERROR === E_ERROR) {
    // E_ERROR is set, do something
}

Upvotes: 1

Related Questions