【问题标题】:Heredoc not workingHeredoc不工作
【发布时间】:2011-04-13 23:26:29
【问题描述】:
<?php

$information = <<<INFO 
Name: John Smith
Address: 123 Main St
City: Springville, CA
INFO;

echo $information;

?>

结果:

解析错误:语法错误,第 3 行出现意外的 T_SL

【问题讨论】:

  • 就我而言,我将整个heredoc字符串缩进了,所以我没有遵循The closing identifier must begin in the first column of the line.的文档
  • @User 很棒的评论,这是我的问题。 PHP 为什么你这么糟糕
  • 如果文件中有不同的heredoc同名但另一个有多余的空格或括号之类的东西,你也会看到这个错误

标签: php heredoc


【解决方案1】:

解析器抱怨是因为在尖括号声明heredoc 之后有空格。您需要确保您实际上遵循了 heredoc 语法,您可以在 PHP 手册网站上找到该语法(特别是:http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc)。

<?php
$information = <<<ENDHEREDOC
this is my text
ENDHEREDOC;
echo $information;

【讨论】:

    【解决方案2】:

    我刚刚编辑了您的问题并修复了无效格式(所以使用 Markdown)。我发现&lt;&lt;&lt;INFO 后面有一个空格字符 - 这会导致错误。

    删除该空间,一切都应该正常工作......好吧 - it has to works fine

    【讨论】:

      【解决方案3】:

      Heredoc 语法有一些我们必须考虑的严格规则;

      1 - 打开标识符后不应有任何字符

      是的

      "$a = <<<HEREDOC"
      

      错误

      "<<<HEREDOC   "   //Remove space after opening identifier;
      

      2 - 在结束标识符之后和之前不应有任何其他字符,除了最后的分隔符分号;。也不允许缩进。

      是的

      "HEREDOC;"
      

      错误

      "HEREDOC  ;"   //Remove space between HEREDOC and ;
      

      错误

      " HEREDOC;"   //Remove space before HEREDOC
      

      错误

      "HEREDOC; "   //Remove space after ;
      

      Heredoc 字符串。 结束;

      【讨论】:

      • 还请考虑并添加结束标识符也不得在换行符之后缩进的要求 - 根据 heredoc 文档。那是我的挂断电话。
      • 我会的,但确实缩进也意味着“2 - 在结束标识符之后和之前不应该有任何其他字符”:)
      【解决方案4】:
      https://repl.it/@CiscoTest/PHP-Heredocs-lesslessless      
          <?php
              //Heredocs start with <<< and a token ended with semi-colon
              print <<< ENDHEREOK
              We used ENDHEREOK "as" our token
                    Looks like it just "print"
                    things "as" it is. Let me loooook at what I just typed
      
              I may add some more! I m gonna end it using ENDHEREOK but any token can be used
              Give it a "try"! Also pay attention to so many double quotes because it is mandatory!
               Also yes "if" you put
              space after token(ENDHEREOK) above, you will get an error, just hit enter key after token!
              Try this on repl.it
              https://repl.it/@CiscoTest/PHP-Heredocs-lesslessless
              ENDHEREOK;
              ?>
      

      【讨论】:

      • 在你的答案中添加解释会让读者更容易理解。
      猜你喜欢
      • 2013-06-29
      • 2013-12-06
      • 2020-12-01
      • 2016-08-24
      • 2011-05-21
      • 2014-08-24
      • 2019-04-27
      • 2020-11-25
      • 2011-05-15
      相关资源
      最近更新 更多