Uppercase Booleans vs. Lowercase in PHP

后端 未结 11 1948
无人共我
无人共我 2020-12-23 02:33

When I was learning PHP, I read somewhere that you should always use the upper case versions of booleans, TRUE and FALSE, because the \"normal\" lo

相关标签:
11条回答
  • 2020-12-23 03:13

    I came across this old question while asking myself the same thing. Good point with define('TRUE', false);define('FALSE', true); Doesn't apply to php5 though. Writing those lines in a php5 code is like writing a comment.

    0 讨论(0)
  • 2020-12-23 03:14

    Here is my TEST on Windows 7x64bit Apache/2.4.9 PHP/5.5.14

    $blockLimit = 50;
    while($blockLimit > 0): $blockLimit--;
    
    //STAR Here ================================================
    
    $msc = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
       echo (FALSE);
    }
    echo 'FALSE took ' . number_format(microtime(true)-$msc,4) . " Seconds\r\n";
    $msc = microtime(true);
    for ($i = 0; $i < 100000; $i++) {
       echo (false);
    }
    echo 'false took ' . number_format(microtime(true)-$msc,4) . " Seconds\r\n";
    
    echo "\r\n --- \r\n";
    //Shutdown ==================================================
    endwhile;
    

    This time FALSE won 20 times. So uppercase is faster in my environment.

    0 讨论(0)
  • 2020-12-23 03:16

    If you intend to use JSON, then RFC7159 says:

    The literal names MUST be lowercase. No other literal names are allowed.

    From the list of backward incompatible changes in PHP 5.6:

    json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification

    According to PSR-2 standard:

    PHP keywords MUST be in lower case.

    The PHP constants true, false, and null MUST be in lower case.

    0 讨论(0)
  • 2020-12-23 03:25

    I am years late to the party but wanted to mention something interesting that isn't in the thread yet. Today I discovered True is also valid, not just true or TRUE. All spellings are equivalent. This is relevant because of the Open API generator for PHP, it uses True. (Which led me to a bewildered state of mind and a search which found this page).

    0 讨论(0)
  • 2020-12-23 03:26

    I've written simple code to check the differences between false and FALSE: Each iteration was doing something that:

        for ($i = 0; $i < self::ITERATIONS; ++$i) {
           (0 == FALSE) ;
        }
    

    Here are the results:

    Iterations: 100000000
    using 'FALSE': 25.427761077881 sec
    using 'false': 25.01614689827 sec
    

    So we can see that performance is very slightly touched by the booleans case - lowercase is faster. But certainly you won't see.

    0 讨论(0)
提交回复
热议问题