【问题标题】:Cannot embed ternary operator into echo statement无法将三元运算符嵌入到 echo 语句中
【发布时间】:2017-09-29 19:04:43
【问题描述】:

这是echo 声明:

    echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> &gt; </a> ";

这里是ternary expression。它的作用是仅在条件为真时将#comment-target 连接到链接的末尾:

( $paginationAddCommentAnchor ?? null) ? '#comment-target' : null

我需要将echo 语句中的#comment-target 替换为ternary expression,但每次尝试都以错误的引文告终。示例尝试:

    echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage . ( $paginationAddCommentAnchor ?? null) ? '#comment-target' : null'> &gt; </a> ";

什么是正确的语法,所以最终结果与最初的 echo 语句相同,但使用三元生成?

【问题讨论】:

  • $paginationAddCommentAnchor ?? null$paginationAddCommentAnchor 相同
  • 使用多行和变量将使您的代码更易于阅读。
  • PHP 在用双引号 (") 括起来的字符串中执行 variables parsing,仅此而已。如果您需要评估一个表达式,那么您必须将其放在字符串之外,并使用 string concatenation operator (.) 将其值与周围的字符串连接起来。
  • @axiac 关于你的第一条评论,如果我不输入$paginationAddCommentAnchor ?? null并且变量为空,则会产生错误。
  • @RobertBrax 没错,它会触发通知。在使用它们之前(在脚本或函数顶部或在它们用于的forif 等块之前,最好使用 NULL(或其他值,取决于变量的用途)初始化所有变量第一次)。它有助于编写更易于阅读和理解的代码(并且错误更少)。

标签: php operators ternary-operator


【解决方案1】:

PHP 在用双引号 (") 括起来的字符串中执行 variables parsing,仅此而已。如果你需要计算一个表达式,那么你必须把它放在字符串之外,并使用string concatenation operator (.)将它的值与周围的字符串连接起来。

或者,要获得更易读的代码,请使用printf()

printf(' <a class="pagination-link" href="%s?page=%s%s> &gt; </a> ',
    $_SERVER['PATH_INFO'], $nextpage,
    $paginationAddCommentAnchor ? '#comment-target' : ''
);

【讨论】:

  • 谢谢,这有帮助,我会选择它作为答案。我按照你说的做了,在外面生成了变量,然后简单地连接起来。
【解决方案2】:

看起来像是试图在一行中做很多事情,而不是正确控制所有部分(引号、字符串连接、三元运算符...)。为了让事情变得清晰和可控,请在单独的块中构建最终字符串:

$tmp_str = $nextpage . ( $paginationAddCommentAnchor ?? null) ? '#comment-target' : '';

echo "<a class=\"pagination-link\" href=\"{$_SERVER['PATH_INFO']}?page=$tmp_str\"></a>";

测试它here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2018-12-26
    • 2016-04-25
    • 2016-06-28
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多