Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function flags, how?

I'm attempting to create a function with flags as its arguments but the output is always different with what's expected :

define("FLAG_A", 1);  
define("FLAG_B", 4);  
define("FLAG_C", 7);  
function test_flags($flags) {  
 if($flags & FLAG_A) echo "A";  
 if($flags & FLAG_B) echo "B";  
 if($flags & FLAG_C) echo "C";   
}  
test_flags(FLAG_B | FLAG_C); # Output is always ABC, not BC  

How can I fix this problem?

like image 505
Teiv Avatar asked Aug 28 '10 05:08

Teiv


People also ask

What are flags in PHP?

They are just constants which map to a number, e.g. SORT_NUMERIC (a constant used by sorting functions) is the integer 1 . Check out the examples for json_encode() . As you can see, each flag is 2n. This way, | can be used to specify multiple flags.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

How will you passing an argument to a function in PHP?

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported. As of PHP 8.0. 0, the list of function arguments may include a trailing comma, which will be ignored.

What is the correct way to create a function in PHP?

The declaration of a user-defined function starts with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}.


1 Answers

Flags must be powers of 2 in order to bitwise-or together properly.

define("FLAG_A", 0x1);
define("FLAG_B", 0x2);
define("FLAG_C", 0x4);
function test_flags($flags) {
  if ($flags & FLAG_A) echo "A";
  if ($flags & FLAG_B) echo "B";
  if ($flags & FLAG_C) echo "C";
}
test_flags(FLAG_B | FLAG_C); # Now the output will be BC

Using hexadecimal notation for the constant values makes no difference to the behavior of the program, but is one idiomatic way of emphasizing to programmers that the values compose a bit field. Another would be to use shifts: 1<<0, 1<<1, 1<<2, &c.

like image 198
Ignacio Vazquez-Abrams Avatar answered Oct 22 '22 09:10

Ignacio Vazquez-Abrams