带有前导零的数字的奇怪行为

2022-01-14 00:00:00 numbers integer php octal

我有一些带有一些整数的 PHP 代码并且一切正常,除非我有 080X 作为整数.当我把它们放在引号中时,一切都很好.

I have some PHP code with some integers and all works fine, except when I have 08 or 0X as integer. It all works fine when I put them in quote.

数字示例:

2      //Works fine
08     //Doesn't work
012    //Doesn't work
"08"   //Works fine again
"012"  //Works fine again

谁能告诉我背后的原因?

Can anyone tell me the reason behind it?

推荐答案

如果你只是写 08 和 09(不带引号)或任何其他以 0 开头的数字,PHP 认为你正在写一个八进制值,而 08 和09 是无效的八进制数.

If you simply write 08 and 09 (without quotes) or any other numeric with a leading 0, PHP believes you're writing an octal value, and 08 and 09 are invalid octal numbers.

http://www.php.net/manual/en/语言.types.integer.php

语法

整数可以指定为十进制(以 10 为底)、十六进制(以 16 为底)、八进制(以 8 为基数)或二进制(以 2 为基数)表示法,前面可选符号(- 或 +).

Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).

从 PHP 5.4.0 开始提供二进制整数文字.

Binary integer literals are available since PHP 5.4.0.

要使用八进制表示法,请在数字前加上 0(零).使用十六进制表示法 在数字前加上 0x.使用二进制符号 在数字前加上 0b.

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

[...]

警告:在 PHP 7 之前,如果在八进制整数(即 8 或 9)中给出了无效数字,则忽略该数字的其余部分.从 PHP 7 开始,会发出解析错误.

Warning: Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

相关文章