views:

40

answers:

2

I'm using the following code from PHPBuilder.com to handle user privileges on my site:

/**
 * Correct the variables stored in array.
 * @param    integer    $mask Integer of the bit
 * @return    array
 */
function bitMask($mask = 0) {
    if(!is_numeric($mask)) {
        return array();
    }
    $return = array();
    while ($mask > 0) {
        for($i = 0, $n = 0; $i <= $mask; $i = 1 * pow(2, $n), $n++) {
            $end = $i;
        }
        $return[] = $end;
        $mask = $mask - $end;
    }
    sort($return);
    return $return;
}

and I'm a bit baffled by the "= 0" part of ($mask = 0) in the function parameter list. What does that do?

+3  A: 

It means that if you call the function like this:

$a = bitMask();

Then $mask will be set to 0.

It is how you set default values to parameter in functions.

Example:

function example($a=0){
    echo "a = $a"; 
}

example(10);
example();

Output:

a = 10
a = 0

If $a did not have a default value set, then calling the function like example() would give a warning.

reference: http://php.net/manual/en/functions.arguments.php (Default argument values)

Michael Robinson
+3  A: 

That's the default value of $mask if no arguments are passed. This also prevents a warning from being generated when the parameter is omitted.

no