What are PHP flags in function arguments?

I noticed that some functions in PHP use flags as arguments. What makes them unique, not just string arguments? I ask because I want to use them in my own custom functions, but I wonder what the process is.

Edit: To summarize, when is it better to create a custom function with flags, and when not?

+6
source share
3 answers

These are just constants that map to a number, for example. SORT_NUMERIC (the constant used by the sort functions) is an integer of 1 .

Check out the examples for json_encode() .

As you can see, each flag is 2 n . Thus, | can be used to indicate multiple flags.

For example, suppose you want to use the JSON_FORCE_OBJECT ( 16 or 00010000 ) and JSON_PRETTY_PRINT ( 128 or 10000000 ) JSON_PRETTY_PRINT .

The bitwise OR ( | ) operator will turn on the bit if the bit of the operand bit is turned on ...

 JSON_FORCE_OBJECT | JSON_PRETTY_PRINT 

... internally ....

 00010000 | 1000000 

... which the...

 10010000 

You can check this with ...

 var_dump(base_convert(JSON_PRETTY_PRINT | JSON_FORCE_OBJECT, 10, 2)); // string(8) "10010000" 

CodePad

Thus, both flags can be set using bitwise operators.

+9
source

Flags are usually integers that are consecutive powers of 2, so each one has one bit equal to 1, and all the others are 0. Thus, you can transfer multiple binary values ​​in one integer form using bitwise operators. See This for more (and probably more accurate) information .

+3
source

They are just a shell with values ​​in it. Therefore, you do not need to worry about what exactly the function needs.

-2
source

Source: https://habr.com/ru/post/910350/


All Articles