如何使用A? PHP 中带有 Heredoc 的 x:y 语法?
我尝试了这个,但只得到了一个语法错误:
<?php
$a = true;
$str = <<< EOF
{$a ? 1 : 2}
EOF;
echo $str;
Is it possible to use such kind of conditional statements inside heredoc?
I tried this but only got a syntax error:
<?php
$a = true;
$str = <<< EOF
{$a ? 1 : 2}
EOF;
echo $str;
Is it possible to use such kind of conditional statement inside heredoc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有。不幸的是,PHP 字符串插值并不是那么健壮。您要么必须连接两个字符串,要么提前将这一点逻辑分配给另一个变量。
Nope. PHP string interpolation is, unfortunately, not quite that robust. You'll either have to concatenate two strings, or assign that little bit of logic to another variable ahead of time.
我会说不。
请参阅此相关问题,了解为什么无法执行函数调用和可能的解决方法:调用 PHP 函数在 HEREDOC 字符串内
关键在于您可能必须将三元运算符分配给定界符之前的变量。
I would say no.
See this related question on why you can't do function calls and possible workarounds: Calling PHP functions within HEREDOC strings
The crux of it is that you will probably have to assign your ternary operator to a variable before the heredoc.
你可以这样做:
You could do something like this:
FWIW,您可以使用heredocs作为三元组的任意一半。如
:
/else 情况,如果您不介意前卫语法,则如
?
/if 情况:对于
?
/如果是这种情况,则此处文档的结束分隔符 (INPUT
) 确实 需要独占一行;:
的缩进是为了清晰起见。FWIW you can use heredocs as either half of a ternary. As the
:
/else case,and if you don't mind avant garde syntax, as the
?
/if case:For the
?
/if case, the heredoc's closing delimiter (INPUT
) does need to be on its own line; the:
's indentation is for clarity.