Heredocs - 使用相同的名称两次?为什么要给它们命名呢?
在 PHP 中尝试这里文档,我意识到这里文档的名称不必是唯一的。因此:
$a = <<<EOD
Some string
EOD;
$b = <<<EOD
A different string
EOD;
是正确的并且行为完全符合您的预期。
这是出于某种原因的不良做法吗?为什么这里文档需要名称/标签(上面的 EOD
),因为您无法通过名称引用它?
Toying with heredocs in PHP, I realized the name of the heredoc does not have to be unique. Thus:
$a = <<<EOD
Some string
EOD;
$b = <<<EOD
A different string
EOD;
is correct and behaves exactly as you would expect.
Is this bad practice for any reason? Why does a heredoc need a name/label (EOD
above) at all, since you can't reference it by the name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您指定的字符串包含
EOD
怎么办?您可以选择标识符以避免与用作字符串的文本块发生冲突。
What if the string you're specifying contains
EOD
?You can select the identifier to avoid conflicts with the chunk of text you're using as a string.
您不会像这样引用它,但它充当标识符来指示heredoc的结束。例如
You don't reference it as such, but it acts as an identifier to indicate the end of the heredoc. e.g.
一个好处是,像 vim 这样的编辑器可以将语法突出显示应用于以 HTML、EOHTML、EOSQL、EOJAVASCRIPT 命名的此处文档,使它们更易于使用...
One benefit is that editors like vim can apply syntax highlighting to heredocs named with HTML, EOHTML, EOSQL, EOJAVASCRIPT making them much prettier to work with...