Home > Backend Development > PHP Tutorial > 关于PHP语法中的 or 与 || 的问题。

关于PHP语法中的 or 与 || 的问题。

WBOY
Release: 2016-06-06 20:10:36
Original
1361 people have browsed it

<code>    $a = 0;    
    $b = 0;    
    
    if($a=3 or $b=3){
        $a++;
        $b++;
    }
    echo $a.",".$b;
</code>
Copy after login
Copy after login

返还值为4,1

<code>    $a = 0;    
    $b = 0;    
    
    if($a=3 || $b=3){
        $a++;
        $b++;
    }
    echo $a.",".$b;</code>
Copy after login
Copy after login

返还值为1,1

why?
第一则中的or语法错了嘛?
wamp环境,php5.5.12

回复内容:

<code>    $a = 0;    
    $b = 0;    
    
    if($a=3 or $b=3){
        $a++;
        $b++;
    }
    echo $a.",".$b;
</code>
Copy after login
Copy after login

返还值为4,1

<code>    $a = 0;    
    $b = 0;    
    
    if($a=3 || $b=3){
        $a++;
        $b++;
    }
    echo $a.",".$b;</code>
Copy after login
Copy after login

返还值为1,1

why?
第一则中的or语法错了嘛?
wamp环境,php5.5.12

1.首先,请查看php.net对所有运算符优先级顺序规定表:http://php.net/manual/zh/language.operators.precedence.php;
2.我们发现||大于=大于or(这里指运算符优先级),且=是右结合顺序;
3.因此,在第二段snippet中的if条件结合顺序应该是if($a=(3||($b=3))),因为php.net上面的链接文档又说了'Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.',翻译一下就是说:运算符的优先级和结合性只是决定了表达式如何分组,却没有指定代码被如何解析执行。。。,所以这里的if条件并不能完全按照运算符的优先级和结合性来判断代码如何解析执行。

关注“PHP技术大全”微信公众号(phpgod),拿起手机,打开微信,轻松一扫下面的二维码,每天成长一点,成就大神就不远。
关于PHP语法中的 or 与 || 的问题。

你以为if($a=3 || $b=3)if(($a=3) || ($b=3))

其实由于运算符优先级的原因,是if($a = ( 3 || ($b = 3) ) )
然后 3 || ($b = 3) 这一句,由于短路特性($b = 3)并没有执行,这句的返回值是布尔类型true,返回给$a,echo出来是1,其自增值也不会改变。$b依然是0,自增成1。

Related labels:
php
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template