无法将三元运算符嵌入 echo 语句
Cannot embed ternary operator into echo statement
这里是 echo
语句:
echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> > </a> ";
这里是 ternary expression
。它所做的是仅当条件为真时才将 #comment-target
连接到 link 的末尾:
( $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'> > </a> ";
正确的语法是什么,所以最终结果与初始 echo
语句相同,但使用三元生成?
PHP variables parsing in the strings enclosed by double quotes ("
) but that's all. If you need to evaluate an expression then you have to put it outside the string and concatenate its value with the surrounding strings using the string concatenation operator (.
).
或者,要获得更易读的代码,请使用 printf()
:
printf(' <a class="pagination-link" href="%s?page=%s%s> > </a> ',
$_SERVER['PATH_INFO'], $nextpage,
$paginationAddCommentAnchor ? '#comment-target' : ''
);
看起来试图在一行中做很多事情,没有正确控制所有部分(引号、字符串连接、三元运算符...)。为了让事情变得清晰和受控,在单独的块中构建最终字符串:
$tmp_str = $nextpage . ( $paginationAddCommentAnchor ?? null) ? '#comment-target' : '';
echo "<a class=\"pagination-link\" href=\"{$_SERVER['PATH_INFO']}?page=$tmp_str\"></a>";
测试一下here。
这里是 echo
语句:
echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> > </a> ";
这里是 ternary expression
。它所做的是仅当条件为真时才将 #comment-target
连接到 link 的末尾:
( $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'> > </a> ";
正确的语法是什么,所以最终结果与初始 echo
语句相同,但使用三元生成?
PHP variables parsing in the strings enclosed by double quotes ("
) but that's all. If you need to evaluate an expression then you have to put it outside the string and concatenate its value with the surrounding strings using the string concatenation operator (.
).
或者,要获得更易读的代码,请使用 printf()
:
printf(' <a class="pagination-link" href="%s?page=%s%s> > </a> ',
$_SERVER['PATH_INFO'], $nextpage,
$paginationAddCommentAnchor ? '#comment-target' : ''
);
看起来试图在一行中做很多事情,没有正确控制所有部分(引号、字符串连接、三元运算符...)。为了让事情变得清晰和受控,在单独的块中构建最终字符串:
$tmp_str = $nextpage . ( $paginationAddCommentAnchor ?? null) ? '#comment-target' : '';
echo "<a class=\"pagination-link\" href=\"{$_SERVER['PATH_INFO']}?page=$tmp_str\"></a>";
测试一下here。