0

我在 Services_JSON php 库中找到了这串代码:

if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
    $stk = array(SERVICES_JSON_IN_OBJ);
    $obj = array();
} else {
    $stk = array(SERVICES_JSON_IN_OBJ);
    $obj = new stdClass();
}

我的问题是关于第一行。单个“&”运算符有什么作用?

4

3 回答 3

4

这是 PHP 位运算AND符: http: //php.net/manual/en/language.operators.bitwise.php

于 2013-03-05T15:49:26.970 回答
0

&& 表示“和”(逻辑运算符),但单个“&”是按位运算符,对位进行二进制比较。

这是来自 php.net 的手册:http: //us2.php.net/manual/en/language.operators.bitwise.php

于 2013-03-05T15:55:48.730 回答
0

不仅要解释 & 的作用,还要解释这个按位与运算符在这种情况下可能用于什么,看看

<?php
define('SOME_FLAG', 1);
define('SERVICES_JSON_LOOSE_TYPE', 2);
define('ANOTHER_FLAG', 4);

foo(0);
foo(7);
foo(SERVICES_JSON_LOOSE_TYPE|ANOTHER_FLAG);

function foo($value) {
    echo "foo($value)\n";

    bar($value, SOME_FLAG);
    bar($value, SERVICES_JSON_LOOSE_TYPE);
    bar($value, ANOTHER_FLAG);

    if ( $value & SOME_FLAG ) {
        echo "  SOME_FLAG set\n";
    }
    else {
        echo "  SOME_FLAG NOT set\n";
    }

    if ( $value & SERVICES_JSON_LOOSE_TYPE ) {
        echo "  SERVICES_JSON_LOOSE_TYPE set\n";
    }
    else {
        echo "  SERVICES_JSON_LOOSE_TYPE NOT set\n";
    }

    if ( $value & ANOTHER_FLAG ) {
        echo "  ANOTHER_FLAG set\n";
    }
    else {
        echo "  ANOTHER_FLAG NOT set\n";
    }
    echo "\n";
} 

function bar($value, $flag) {
    printf("  value|  %08s (%d)\n", decbin($value), $value);
    printf("  flag |& %08s (%d)\n", decbin($flag), $flag);
    printf("  and  |= %08s (%d)\n", decbin($value & $flag), $value & $flag);
    echo "\n";
}

输出是

foo(0)
  value|  00000000 (0)
  flag |& 00000001 (1)
  and  |= 00000000 (0)

  value|  00000000 (0)
  flag |& 00000010 (2)
  and  |= 00000000 (0)

  value|  00000000 (0)
  flag |& 00000100 (4)
  and  |= 00000000 (0)

  SOME_FLAG NOT set
  SERVICES_JSON_LOOSE_TYPE NOT set
  ANOTHER_FLAG NOT set

foo(7)
  value|  00000111 (7)
  flag |& 00000001 (1)
  and  |= 00000001 (1)

  value|  00000111 (7)
  flag |& 00000010 (2)
  and  |= 00000010 (2)

  value|  00000111 (7)
  flag |& 00000100 (4)
  and  |= 00000100 (4)

  SOME_FLAG set
  SERVICES_JSON_LOOSE_TYPE set
  ANOTHER_FLAG set

foo(6)
  value|  00000110 (6)
  flag |& 00000001 (1)
  and  |= 00000000 (0)

  value|  00000110 (6)
  flag |& 00000010 (2)
  and  |= 00000010 (2)

  value|  00000110 (6)
  flag |& 00000100 (4)
  and  |= 00000100 (4)

  SOME_FLAG NOT set
  SERVICES_JSON_LOOSE_TYPE set
  ANOTHER_FLAG set

这是一种测试是否在值中设置了某个标志的方法。
查看 php 文档,例如preg_match_all的文档:

旗帜
    可以是以下标志的组合 [...]
    PREG_PATTERN_ORDER [...]
    PREG_SET_ORDER [...]
    PREG_OFFSET_CAPTURE [...]

你会Can be a combination of the following flags...在文档中多次找到这个东西。这些函数/方法背后的代码正是使用按位与运算符进行的那种检查。

于 2013-03-05T16:19:51.560 回答