Parse error: Invalid numeric literal

Parse error: Invalid numeric literal

我在 运行 以下代码时出现以下错误:

代码:

<?php
    $a = array(00001, 00008, 00009, 00012);
    print_r($a);
?>

错误:

Parse error: Invalid numeric literal.

为什么会出现这个问题,我该如何解决?

这是因为 PHP7 中对整数(特别是八进制)的处理方式发生了变化(与 PHP5 相反)。

来自文档(来自 PHP7 迁移)

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

来自整数的文档

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.

将它们用作字符串或实际整数

$a = array(1, 8, 9, 12); // Integers
$a = array("00001", "00008", "00009", "00012"); // Strings

这是因为所有以 0 开头的数字都被视为八进制值,每个位置 (0-7) 的上限为 8 位数字。作为 stated in the PHP manual,他们现在 (7.x) 不再默默删除无效数字,而是产生上述警告。

虽然你为什么要这样写你的数字?如果前导零很重要,那么它不是您拥有的数字,而是一个字符串。如果您需要对它们进行计算,就好像它们是数字一样,那么您需要在将值输出到客户端时添加前导零。
这可以用 printf()sprintf() 来完成,像这样:

$number = 5;
printf ("%05d", $number);

see the manual for more examples.

有时,表面上有效的数字文字会被检测为无效的数字文字。

这是自 php5.4

以来的回归

您可以通过将数组更改为:

来解决此问题
$a =array(1,8,9,12);   

$a = array('0001','0008','0009','0012'); //alternative method for fix

参考:https://bugs.php.net/bug.php?id=70193

decimal     : [1-9][0-9]*(_[0-9]+)*|0

octal       : 0[0-7]+(_[0-7]+)*

来自 document 将值视为十进制和八进制的正则表达式在上面给出

在此场景中,值为 00008、00009 也未通过八进制或十进制验证。由于给出错误,将参数解析为字符串正在部分解决问题。

Note: In PHP any number starts from zero considered as octal but 8 and 9 will not used in octal number resulting throw this error.