Home > php教程 > php手册 > body text

浅谈PHP第一弹---php位运算符”|”和逻辑运算符”||”遇到的问题

WBOY
Release: 2016-06-13 10:48:33
Original
898 people have browsed it

在php中,”|”为php位运算符,”||”为逻辑运算符
位运算符代码:
$a=0;
$b=0;
if($a=3 | $b=3){
$a++;
$b++;
}
echo $a.','.$b; //输出 4,4
?>
对比一下代码,以下为逻辑运算符的代码:
$a=0;
$b=0;
if($a=3 || $b=3){
$a++;
$b++;
}
echo $a.','.$b; //输出 1,1
?>

在上述两个例子中,第一个例子中,”$a=3 | $b=3″,由于”|”的优先级高于赋值运算符,所以运算顺序可写为 “$a=(3 | $b=3)”,首先$b被赋值为3,而$a被二进制数0100 | 0100 的结果赋值,仍为0100,所以$a此时被赋值为0100,也就是十进制的3,赋值成功,返回true,执行if代码块中的内容,$a自加,$b也自加, 所以,$a=4,$b=4


第二个例子中,同样可以看做是”$a = (3 || $b = 3)”,首先3||$b=3返回true,”||”造成短路,”||”前的3已经为真,”$b=3″不再执行,所以此时$b仍为0,$a为布尔类型的 true,,赋值成功,返回true,执行if代码块中的内容,$a++还为true,$b++为1,所以,$a=1,$b=1


摘自 zdrjlamp
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!