0

Is there a way of defining some variables with true or false and passing them in collectively into a function as a parameter like in C++ like flags to turn sections of a function on or off using the bitwise inclusive or... For example:

// Declare

define( "ADMIN", TRUE);
define( "CLIENT", TRUE);

function Authenticated( $flags )
{
    // Not sure what would go here ? but something like
    // If ADMIN then
    // If CLIENT then
    // If ADMIN | CLIENT then
}

// Call

Authenticated( ADMIN | CLIENT );

2 Answers 2

0

You can define constants in your class and make sure their values are separate bits:

class Authentication
{
    const ADMIN  = 0x0001;
    const CLIENT = 0x0002;
}

function Authenticated($flags)
{
    $adminFlag = $flags & Authentication::ADMIN;
    $clientFlag = $flags & Authentication::CLIENT;

    if ($adminFlag && $clientFlag) ...
    else if ($adminFlag) ...
    else if ($clientFlag) ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Jon or anyone, why did you do 4 places for the bit number you put in? I know you can put 1, 2, 4, 6 etc and that is bad because it does not suggest you will use as bit fields.. but 0x1, 0x2, 0x4, 0x6 work too... was there any reason why you decided to prefix the 3 0's?
@JamesT: I just like having everything nicely lined up, and 4 digits 16 flags) is a good compromise between not writing too much and not leaving enough room to expand later. Just preference.
thanks mate :) - I just applied the same methodology to some javascript!!! I didn't know you could declare bit variables lol!
Alternatively, binary integer literals are available since PHP 5.4.0, allowing to use 0b0001, 0b0010, 0b0100. Flags must be powers of 2 in order to bitwise-or together properly. So slight correction on the comment above, that is 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, etc. Alternatively you can use the bitwise shift operator like 1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7, 1<<8, 1<<9, 1<<10, 1<<11, etc...
0
define("ADMIN", 0x0001);
define("CLIENT", 0x0002);

And now you can use them as actual bitflags.

1 Comment

can you supply an example? I can then beaver away at it :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.