drxm5014 2016-10-17 15:05
浏览 22
已采纳

三元运算符中的评估顺序

I have two snippets of php:

function prefix_shortcode_statement_conditional( $atts, $content = null ) {
    return '<li class="some-class">' . $content == null ? '' : $content . '</li>';
}

function prefix_shortcode_statement( $atts, $content = null ) {
    return '<li class="some-class">' . $content . '</li>';
}

The first snippet has a conditional statement to return an empty string as the <li> content, while the second one merely returns the content wrapped in <li>.

prefix_shortcode_statement_conditional output

Lorem Ipsum ...

prefix_shortcode_statement output

<li class="some-class">
    Lorem Ipsum ... 
</li>

As you can see, only the function without the conditional statement properly generates the <li> element. Why does one snippet generate the code, but not the other?


Wrapping the conditional in parentheses resolves the issue, but fails to help me understand why the issue arose in the first place.

return '<li class="some-class">' . ($content == null ? '' : $content) . '</li>';

As far as I can tell, php should interpret ending </li> as part of the conditional statement, but fails to. Instead of adding $content . '</li>' to the output, it instead just returns $content and at some level (browser, wordpress, etc), the first <li> is removed from the outputted html.

Interestingly, wrapping the $content and the </li> also fails to display the <li>...</li>.

return '<li class="mep-testimonial-li">' . $content == null ? '' : ($content . '</li>');

I would expect to only see this issue when $content is null, so the referenced </li> would be omitted and the formatting would shift.

  • 写回答

2条回答 默认 最新

  • dongye3917 2016-10-17 15:15
    关注

    In PHP, as in other languages, concatenation have a higher precedence than comparison, so:

    return '<li class="some-class">' . $content == null ? '' : $content . '</li>';
    

    Will always print $content . '</li>', since '<li class="some-class">' . $content will never be falsy ou null.
    This may lead to invalid markup and not be rendered correctly in the browser.

    Always wrap your ternaries in parenthesis.

    return '<li class="some-class">' . ($content == null ? '' : $content) . '</li>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应