Php 无法将三元运算符嵌入echo语句

Php 无法将三元运算符嵌入echo语句,php,operators,ternary-operator,Php,Operators,Ternary Operator,以下是echo语句: echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> &gt; </a> "; 我需要在echo语句中将#comment target替换为三元表达式,但每一次尝试都会以一团带错误引语的丑陋泥球而告终。尝试示例: echo " <a class=\"pagination-link

以下是
echo
语句:

    echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> &gt; </a> ";
我需要在
echo
语句中将
#comment target
替换为
三元表达式
,但每一次尝试都会以一团带错误引语的丑陋泥球而告终。尝试示例:

    echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage . ( $paginationAddCommentAnchor ?? null) ? '#comment-target' : null'> &gt; </a> ";
echo”“;
正确的语法是什么,这样最终的结果与初始的
echo
语句相同,但是由三元语句生成的?

PHP使用双引号(
)括起来的字符串但仅此而已。如果需要计算表达式,则必须将其放在字符串外部,并使用

或者,要获得更可读的代码,请使用:

printf(“”,
$\u服务器['PATH\u INFO'],$nextpage,
$paginationAddCommentAnchor?“#注释目标”:”
);

看起来像是试图在一行中完成很多事情,但没有正确控制所有部分(引号、字符串连接、三元运算符…)。要保持清晰和可控,请在单独的块中构建最终字符串:

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

echo "<a class=\"pagination-link\" href=\"{$_SERVER['PATH_INFO']}?page=$tmp_str\"></a>";
$tmp_str=$nextpage.($paginationAddCommentAnchor??null)?“#注释目标”:”;
回声“;

测试它。

$paginationAddCommentAnchor??null
$paginationAddCommentAnchor
相同,使用多行和变量将使代码更易于阅读。PHP在双引号(
)括起来的字符串中使用PHP,但仅此而已。如果需要对表达式求值,则必须将其放在字符串外部,并使用@axiac将其值与周围的字符串连接起来。如果我没有放置
$paginationAddCommentAnchor??null
且变量为空,则会生成错误。@RobertBrax如果您是对的,则会触发通知。在使用所有变量之前,最好使用
NULL
(或其他值,取决于变量的用途)初始化所有变量(在脚本或函数顶部,或在
for
if
etc块之前,第一次使用它们)。它有助于编写更易于阅读和理解(错误更少)的代码。谢谢,这很有帮助,我将选择它作为答案。我按照你说的做了,在外部生成了变量,然后简单地将其合并。
printf(' <a class="pagination-link" href="%s?page=%s%s> &gt; </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>";