我在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();
}
我的问题是关于第一行。单个“&”运算符有什么作用?
答案 0 :(得分:4)
这是PHP按位AND
运算符:http://php.net/manual/en/language.operators.bitwise.php
答案 1 :(得分:0)
&安培;&安培;意味着"和" (逻辑运算符)但是单个"&"是一个按位运算符,它对位进行二进制比较。
以下是php.net的手册: http://us2.php.net/manual/en/language.operators.bitwise.php
答案 2 :(得分: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的文档:
flags Can be a combination of the following flags [...] PREG_PATTERN_ORDER [...] PREG_SET_ORDER [...] PREG_OFFSET_CAPTURE [...]
您将在文档中多次发现此Can be a combination of the following flags...
事件。这些函数/方法背后的代码完全使用按位和运算符进行检查。