Home > Backend Development > PHP7 > body text

Numeric Literal Separator in PHP 7.4

藏色散人
Release: 2023-02-17 13:18:01
Original
3047 people have browsed it

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?
Copy after login

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

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

建议

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

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

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

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

限制

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

_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
Copy after login

PHP功能不受影响

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

var_dump(1_000_000); // int(1000000)
Copy after login

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

向后不兼容的更改

没有。

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

The above is the detailed content of Numeric Literal Separator in PHP 7.4. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template