>  기사  >  백엔드 개발  >  关于PHP语法中的 or 与 || 的问题。

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

WBOY
WBOY원래의
2016-06-06 20:10:361310검색

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

返还值为4,1

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

返还值为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>

返还值为4,1

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

返还值为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。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.