PHP:是否可以以某种方式将 HTML 嵌入到三元运算符的中间?
例如,我可以做如下的事情吗?
<? $foobar = 1;
$foobar==0 ? ?>
<span>html goes here.</span>
<? : ?>
<span>something else.</span>
<? ; ?>
该代码将不起作用。所以我猜这是不可能的,或者是吗?
For example, can I do something like the following?
<? $foobar = 1;
$foobar==0 ? ?>
<span>html goes here.</span>
<? : ?>
<span>something else.</span>
<? ; ?>
That code won't work. So i'm guessing it's not possible, or is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用
switch
。示例
但是如果您仍然想使用三元运算符来执行此操作,请像这样操作:
I would recommend to use
switch
.Example
But if you still want to do it with ternary operator, do it like this:
我认为使用这样的三元运算符是没有意义的,我的意思是,您要花费 6 行代码来执行此操作,因此不再紧凑。
我建议您将其重写为 if/else。
此致。
哈!
i think is pointless to use the ternary operator like this, i mean, you are expending 6 lines of code for doing it so is not compact anymore.
I would recomend you to rewrite it as as if/else.
Best regards.
HTH!
您不能像这样嵌入 HTML,因为您会过早终止三元表达式,从而导致解析错误。
另一种 if-else 结构更具可读性。对于额外的几个字符,您将获得更容易理解的代码块:
您也可以使用大括号语法,但我不喜欢在代码周围看到杂散的、未标记的
}
。You cannot embed HTML like that, because you are terminating the ternary expression prematurely, causing a parse error.
The alternative if-else construct is much more readable. For an extra few characters you get a much more easily-understood block of code:
You can use the curly-brace syntax too but I don't like seeing stray, unlabeled
}
s around my code.使用字符串的替代方案。
Alternative using strings.