JS vs PHP: assignment operator precedence when used with logical-or

前端 未结 3 738
猫巷女王i
猫巷女王i 2020-12-14 19:09

(PHP has || and OR. JS only has ||.)

JS. According to MDN || has higher precedence than =<

3条回答
  •  眼角桃花
    2020-12-14 19:56

    The expression $a || $a = 1; is equivalent to this:

    if ( $a != true ) {
        $a = 1;
    }
    

    A very common variant on the idea is used for poor-mans debugging:

    $debug = true;
    
    // Thousands of lines of code
    
    $debug && printf("Foo: {$foo}");
    
    // More code
    
    $debug && printf("Bar: {$bar}");
    

    In this paradigm, only the $debug statement needs to be set to true/false to enable/disable debugging. I'm not advocating this type of debugging, but I've seen it quite a few times.

提交回复
热议问题