I noticed that some functions in PHP use flags as arguments. What makes them unique instead of plain string arguments? I'm asking since I want to use them on my own custom functions but am curious as to what the process is for doing so.
Edit: TO summarize, when is it best to create a custom function with flags and when is it not?
They are just constants which map to a number, e.g.
SORT_NUMERIC
(a constant used by sorting functions) is the integer1
.Check out the examples for
json_encode()
.As you can see, each flag is 2n. This way,
|
can be used to specify multiple flags.For example, suppose you want to use the flag
JSON_FORCE_OBJECT
(16
or00010000
) andJSON_PRETTY_PRINT
(128
or10000000
).The bitwise operator OR (
|
) will turn the bit on if either operand's bit is on......is internally....
...which is...
You can check it with...
CodePad.
This is how both flags can be set with bitwise operators.
Usually flags are integers that are consecutive powers of 2, so that each has one bit set to 1 and all others to 0. This way you can pass many binary values in a single integer using bit-wise operators. See this for more (and probably more accurate) information.