• 技术文章 >后端开发 >PHP7

    PHP 7.4中的数值文字分隔符(Numeric Literal Separator )

    藏色散人藏色散人2019-11-30 18:01:31原创1095
    PHP 7.4中的数值文字分隔符(Numeric Literal Separator )

    介绍

    人类的眼睛并没有为快速解析长数字序列而优化。因此,缺乏可视分隔符会使读取和调试代码的时间更长,并可能导致意外的错误。

    1000000000;   // Is this a billion? 100 million? 10 billion?
    ‪107925284.88;‬ // What scale or power of 10 is this?

    此外,没有视觉分隔符,数字文字无法传达任何额外的信息,例如财务数量是否以美分存储:

    $discount = 13500; // Is this 13,500? Or 135, because it's in cents?

    建议

    通过支持数字文字中的下划线来可视化地分隔数字组,从而提高代码的可读性。

    $threshold = 1_000_000_000;  // a billion!
    $testValue = ‪107_925_284.88; // scale is hundreds of millions
    $discount = 135_00;          // $135, stored as cents

    下划线分隔符可用于PHP支持的所有数值文字符号中:

    6.674_083e-11; // float
    299_792_458;   // decimal
    0xCAFE_F00D;   // hexadecimal
    0b0101_1111;   // binary
    0137_041;      // octal

    限制

    唯一的限制是数字文字中的每个下划线必须直接位于两个数字之间。这条规则意味着下面的用法都不是有效的数字文字:

    _100; // already a valid constant name
     
    // these all produce "Parse error: syntax error":
    100_;       // trailing
    1__1;       // next to underscore
    1_.0; 1._0; // next to decimal point
    0x_123;     // next to x
    0b_101;     // next to b
    1_e2; 1e_2; // next to e

    PHP功能不受影响

    在数字文字的数字之间添加下划线不会改变其值。下划线在词法分析阶段被删除,因此运行时不受影响。

    var_dump(1_000_000); // int(1000000)

    此RFC不会将字符串的行为更改为数字转换。数字分隔符旨在提高代码的可读性,而不是改变输入的处理方式。

    向后不兼容的更改

    没有。

    翻译:https://wiki.php.net/rfc/numeric_literal_separator

    以上就是PHP 7.4中的数值文字分隔符(Numeric Literal Separator )的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:PHP 7.4
    上一篇:PHP 7.4中的预加载(Opcache Preloading) 下一篇:PHP 7.4中的弱引用(Weak References )
    大前端线上培训班

    相关文章推荐

    • PHP 7.4.0刚刚发布!一起看看有哪些新特性• PHP 7.4中的箭头函数(Arrow Functions)• PHP 7.4中的类型属性(Typed Properties)• PHP 7.4中的预加载(Opcache Preloading)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网