關於PHP文法中的 or 與 || 的問題。

來源:互聯網
上載者:User
關鍵字 php
    $a = 0;        $b = 0;            if($a=3 or $b=3){        $a++;        $b++;    }    echo $a.",".$b;

返還值為4,1

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

返還值為1,1

why?
第一則中的or文法錯了嘛?
wamp環境,php5.5.12

回複內容:

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

返還值為4,1

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

返還值為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),拿起手機,開啟,輕鬆一掃下面的二維碼,每天成長一點,成就大神就不遠。

你以為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。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.