Logical operators and assignment operator precedence in PHP.
P粉176980522
P粉176980522 2023-08-07 11:55:52
0
1
486
<p>I recently found it in a passage like this:</p> <pre class="brush:php;toolbar:false;">$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;</ pre> <p>This code snippet produces output 1:3. By looking at the operator precedence table, I found that the logical operators || and && have higher precedence than the assignment operator =. Therefore, the first expression should be treated as $x = ($y || 2) = 3; which makes $x = (2 && $y) = 3; and finally evaluates to $x = false = 3;. Second, the assignment operator has right-ordering, so the interpreter should try to do false = 3, which is obviously illegal. So, in my opinion, the above mentioned code snippet should fail to compile and should throw a parse or runtime error. But instead, this snippet produced 1:3. This means that what the interpreter does is: </p> <blockquote> <p>a) $y=3</p> <p>b) 2 && $y</p> <p>c) $x = (2 && $y)</p> </blockquote> <p>Why do this instead of based on operator precedence?</p>
P粉176980522
P粉176980522

reply all(1)
P粉615829742

The operator precedence table you provided states as a separate comment:

So, in effect, the assignment within the expression will be treated as a subexpression. How and when this is done is not clearly stated in the documentation, which simply states that "similar" expressions will work this way.

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!