Andrew Heath Andrew Heath - 2 months ago 10
PHP Question

assignment operator (=) within a function's parameter list?

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?

Answer

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)