ThinkPHP5报 Namespace declaration statement has to be the very first statement or after any declare call in the script 错误的解决方法

错误介绍

一般这个错误用PhpStorm开发的人很少出现,如果在namespace之前输出内容的话,IDE会直接提示错误,一眼就能看出来。但是,偶尔拿到别人的代码,可能文件有BOM头,同时也检查不到之前输出了什么,就让小白有点头疼了。
错误示例截图

错误的可能性

以下为两种可能:

  • 第一种,在namespace之前手动输出了内容.
    在namespace之前手动输出了内容
  • 第二种,文件存在BOM头。
    文件存在BOM头

解决方法

  • 对于自己手动输出内容的删除相关代码就可以了。
  • 对于有BOM头的可参考上图,在PhpStorm内点击右键,会有一个Remove BOM的选项,点一下就去掉了。
  • 同时提供一个去除BOM头的php文件,可以直接复制使用。代码如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    <?php
    /**
    * 去除BOM头代码
    */
    //需要遍历的目录
    if (isset($_GET['dir'])) {
    $basedir = $_GET['dir'];
    } else {
    $basedir = '.';
    }
    //是否自动去除BOM头
    $auto = 1;

    check_dir($basedir);

    //遍历
    function check_dir($basedir)
    {
    if ($dh = opendir($basedir)) {
    while (($file = readdir($dh)) !== false) {
    if ($file != '.' && $file != '..') {
    if (!is_dir($basedir . "/" . $file)) {
    echo "filename: $basedir/$file " . check_bom("$basedir/$file") . " <br/>";
    } else {
    $dir_name = $basedir . "/" . $file;
    check_dir($dir_name);
    }
    }
    }
    closedir($dh);
    }
    }

    //检查BOM头
    function check_bom($filename)
    {
    global $auto;
    $contents = file_get_contents($filename);
    $charset[1] = substr($contents, 0, 1);
    $charset[2] = substr($contents, 1, 1);
    $charset[3] = substr($contents, 2, 1);

    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
    if ($auto == 1) {
    $rest = substr($contents, 3);
    rewrite($filename, $rest);
    return ('<span style="color: red">找到BOM头并且已去掉。</span>');
    }
    return ('<span style="color: red">找到BOM头。</span>');
    }
    return ("没有找到BOM头");
    }

    //重新写入无BOM头的文件
    function rewrite($filename, $data)
    {
    $file = fopen($filename, "w");
    flock($file, LOCK_EX);
    fwrite($file, $data);
    fclose($file);
    }