开发者

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) i开发者_C百科n the function parameter list. What does that do?


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)


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.


Michael's response is correct. To add to it, take note that the assignment will not have an affect on the original variable modified. Here is his code with a few more assignments / echos to illustrate this:

function example($a=0){
    echo "Entering function: a = $a\n"; 
    $a = 3;
    echo "End of function: a = $a\n";
}

$a = 7;
example(10);
echo "Outside of Function: a = $a\n";

Outputs

Entering function: a = 10
End of function: a = 3
Outside of Function: a = 7
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜