Heim  >  Artikel  >  Backend-Entwicklung  >  Numerisches Literaltrennzeichen in PHP 7.4

Numerisches Literaltrennzeichen in PHP 7.4

藏色散人
藏色散人Original
2019-11-30 14:21:172975Durchsuche

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

Das obige ist der detaillierte Inhalt vonNumerisches Literaltrennzeichen in PHP 7.4. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn