Search code examples
php-7.2

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


I have created a php test script test.php with the following code :

<?php
declare(strict_types=1);

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

print(sum(2, 3));

Then when I try to run it, I am getting this fatal error:

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

I am using PHP 7.2.4 on Wampserver 3.1.3 and I am accessing the script through my browser.


Solution

  • Did you save it in an editor that outputs a UTF-8 BOM? It's a few invisible bytes at the start of the file which mark it as Unicode, but PHP doesn't recognise it.

    Try opening the file in Notepad, going to Save As and choosing the ANSI encoding.

    Also make very sure there are no lines before the opening tag. It sounds like there is one.