获取:我尝试在 PHP 文件上使用 declare(strict_types=1) 时出现致命错误

Getting : Fatal error while I am trying to use the declare(strict_types=1) on my PHP file

我创建了一个 php 测试脚本 test.php,代码如下:

<?php
declare(strict_types=1);

function sum(int $a, int $b) : int {
      return $a + $b ;
}

print(sum(2, 3));

然后,当我尝试 运行 它时,出现了这个致命错误:

Fatal error: strict_types declaration must be the very first statement in the script in C:\wamp\www\test.php on line 2

我在 Wampserver 3.1.3 上使用 PHP 7.2.4,我正在通过浏览器访问脚本。

您是否将其保存在输出 UTF-8 BOM 的编辑器中?它是文件开头的几个不可见字节,将其标记为 Unicode,但 PHP 无法识别它。

尝试在记事本中打开文件,转到“另存为”并选择 ANSI 编码。

还要确保开始标记前没有行。好像有一个。

如果开头有多余的空格,也会出现这个错误。应特别删除 <?php

之前的空格

我使用脚本标签来解决这个问题。 <script>declare(strict_types=1);</script>。 记住这个,放在正文的第一个。