Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are PHP flags in function arguments?

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?

like image 424
enchance Avatar asked Mar 09 '12 14:03

enchance


People also ask

What are flags in PHP?

The ArrayObject::setFlags() function is an inbuilt function in PHP which is used to set the flag to change the behavior of the ArrayObject. Syntax: void ArrayObject::setFlags( int $flags ) Parameters: This function accepts single parameter $flags which holds the behavior of new ArrayObject.

What is function argument PHP?

PHP Function ArgumentsAn argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument ($fname).

What is default argument in function explain with example in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call. Example: PHP.

What is PHP default argument?

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.


2 Answers

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.

like image 81
bububaba Avatar answered Nov 15 '22 14:11

bububaba


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.

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

The bitwise operator OR (|) will turn the bit on if either operand's bit is on...

JSON_FORCE_OBJECT | JSON_PRETTY_PRINT

...is internally....

00010000 | 1000000

...which is...

10010000

You can check it with...

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

CodePad.

This is how both flags can be set with bitwise operators.

like image 36
alex Avatar answered Nov 15 '22 12:11

alex