HereDoc无法工作

15
<?php

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

echo $information;

?>

结果:

解析错误:第3行出现意外的T_SL符号


1
在我的情况下,我将整个heredoc字符串缩进了,所以我没有遵循文档中说的“结束标识符必须从行的第一列开始”。 - User
1
@User 很好的评论,这正是我的问题。PHP为什么这么糟糕。 - user562566
如果文件中有另一个名称相同但多了一个空格、括号或其他字符的heredoc,您也会看到此错误。 - William Entriken
4个回答

29

5

在使用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字符串。

END;


请考虑并添加要求,即结束标识符在换行符后也不能缩进 - 正如heredoc文档所述。这是我的困扰所在。 - Shmack
我会的,但是“2-在结束标识符之后和之前不应该有任何其他字符”中也包括缩进 :) - Erdinç Çorbacı

4
我刚刚编辑了你的问题并修复了无效的格式(SO使用Markdown)。我发现在<<<INFO后面有一个空格字符,这是导致错误的原因。
删除该空格,一切应该正常工作...好吧-它必须正常工作

0
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;
        ?>

在你的答案中添加解释将使读者更容易理解它。 - Acapulco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接