【问题标题】:Only output on one side of ternary in PHP, is there a cleaner way to write this?在 PHP 中只输出三进制的一侧,有没有更简洁的方法来写这个?
【发布时间】:2014-11-04 15:07:34
【问题描述】:

我有以下代码行:

<input id="b_first_name" type="text" name="b_first_name" class="required"
    value="<?= $this->settings['fill_form'] ? "Bob" : "" ?>">

有没有更简洁的方法来写这个?我不喜欢写一侧不需要输出的三元组,感觉很脏。仅当设置“fill_form”设置为 true 时,我才希望输出“Bob”。我希望我能做这样的事情,但都不管用:

<input id="b_first_name" type="text" name="b_first_name" class="required"
    value="<?= $this->settings['fill_form'] ? "Bob" ?>">

<input id="b_first_name" type="text" name="b_first_name" class="required"
    value="<?= if ($this->settings['fill_form']) "Bob" ?>">

【问题讨论】:

  • 没有更清洁的方法。另一种选择是&lt;? if ($this-&gt;settings['fill_form']) echo "Bob" ?&gt;
  • &lt;?php if ($this-&gt;settings['fill_form']) echo "Bob";?&gt; 如果您更喜欢第一个选项,它将起作用。或:&lt;?=!$this-&gt;settings['fill_form'] ?:'Bob';?&gt;

标签: php ternary-operator


【解决方案1】:

缺少回声。

<input id="b_first_name" type="text" name="b_first_name" class="required"
value="<?php if ($this->settings['fill_form']) echo "Bob";  ?>">

但我也会把括号放在一边

<input id="b_first_name" type="text" name="b_first_name" class="required"
value="<?php if ($this->settings['fill_form']) { echo "Bob"; } ?>">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多