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 );
Jimmyt1988
  • 20,466
  • 41
  • 133
  • 233

2 Answers2

0
define("ADMIN", 0x0001);
define("CLIENT", 0x0002);

And now you can use them as actual bitflags.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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) ...
}
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 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? – Jimmyt1988 Jun 12 '13 at 16:06
  • @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. – Jon Jun 12 '13 at 16:21
  • thanks mate :) - I just applied the same methodology to some javascript!!! I didn't know you could declare bit variables lol! – Jimmyt1988 Jun 12 '13 at 16:22
  • Alternatively, [binary integer literals are available since PHP 5.4.0](http://php.net/manual/en/language.types.integer.php), 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... – pjvleeuwen Dec 29 '16 at 08:09