PHP 中有两个连续的 heredocs?

Two sequential heredocs in PHP?

以下代码有什么问题:

static function queryVariables($variable_name)
    {

        $query = <<<SQL
SELECT * 
  FROM variables v 
    WHERE v.nam = '$variable_name'
SQL;    

    $ans = self::$conn->select($query);


      $query = <<<SQL
SELECT v.id, v.nam variable_nam, v.descr variable_descr, us.id subset_id, us.unit_id, us.ord, us.nam subset_nam, us.color, us.min_value, us.max_value 
  FROM variables v 
    LEFT JOIN unit_subsets us ON v.unit_id = us.unit_id
    WHERE v.nam = '$variable_name'
SQL;

        $ans = self::$conn->select($query);

        return $ans;
    }

我知道这在逻辑上是不正确的,因为覆盖了 $query 变量。但问题是:为什么它不明白这里有两个 heredoc?它将整个块视为一个 heredoc 并抛出

Undefined variable: ans

异常,因为它试图将 $ans 嵌入到 heredoc 中。

如何修复?

我在 SQL; 结束标识符后看到空格。你不能拥有它们。分号必须是换行符之前的最后一个字符。

SQL;    
    ^^^^^^^

根据documentation

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

documentation中解释的很清楚:

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.

在发布的代码中第一次出现 SQL; 之后,在同一行上,是一堆空格。删除它们,它将按您的预期工作。