【发布时间】:2017-09-29 19:04:43
【问题描述】:
这是echo 声明:
echo " <a class=\"pagination-link\" href='{$_SERVER['PATH_INFO']}?page=$nextpage#comment-target'> > </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'> > </a> ";
什么是正确的语法,所以最终结果与最初的 echo 语句相同,但使用三元生成?
【问题讨论】:
-
$paginationAddCommentAnchor ?? null与$paginationAddCommentAnchor相同 -
使用多行和变量将使您的代码更易于阅读。
-
PHP 在用双引号 (
") 括起来的字符串中执行 variables parsing,仅此而已。如果您需要评估一个表达式,那么您必须将其放在字符串之外,并使用 string concatenation operator (.) 将其值与周围的字符串连接起来。 -
@axiac 关于你的第一条评论,如果我不输入
$paginationAddCommentAnchor ?? null并且变量为空,则会产生错误。 -
@RobertBrax 没错,它会触发通知。在使用它们之前(在脚本或函数顶部或在它们用于的
for、if等块之前,最好使用NULL(或其他值,取决于变量的用途)初始化所有变量第一次)。它有助于编写更易于阅读和理解的代码(并且错误更少)。
标签: php operators ternary-operator