php通过引用分配,通过引用传递

时间:2012-06-03 16:33:15

标签: php

我了解通过引用分配$b = &$a)和通过引用传递变量 function foo( &$var )

我不明白这是如何运作的:return($var & 1) & return(!($var & 1))?我看到了这个片段here

<?php

    function odd($var)
    {
        // returns whether the input integer is odd
        return($var & 1);
    }

    function even($var)
    {
        // returns whether the input integer is even
        return(!($var & 1));
    }

    $array1 = array(1, 2, 3, 4, 5);
    $array2 = array(6, 7, 8, 9, 10, 11, 12);

    print_r(array_filter($array1, "odd"));
    // Array ( [0] => 1 [2] => 3 [4] => 5 ) //1,3,5 ..odd

    echo "<br>";

    print_r(array_filter($array2, "even")); 
    //Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 ) 6,8,10,12...even

    // I tested with these variables
    echo "<br><br>";

    $var=22;

    echo(odd($var));     //prints 0
    var_dump(odd($var)); //int 0


    $var=11;

    echo (even($var));   //prints nothing
    var_dump(even($var));//boolean false

?> 

1 个答案:

答案 0 :(得分:5)

&此处为bitwise "and",而非参考运算符。 & 1检查它设置的最低有效位。对于奇数,它被设置,对于偶数,它不是。