不同的串联方法返回不同的输出


Different methods of concatenation return different output

我绝对不是PHP专家,但我认为以下代码片段输出相同的HTML。但他们没有。

echo '<a href="';
the_permalink();
echo '" title="';
the_title();
echo '"><i class="genericon-standard"></i></a>';

返回(应返回):

<a href="http://my-site.com/?p=1" title="Hallo wereld!"><i class="genericon-standard"></i></a>

但是更短的代码

echo '<a href="' . the_permalink() . '" title="' . the_title() . '"><i class="genericon-standard"></i></a>';

返回

http://my-site.com/?p=1Hallo wereld!<a href="" title=""><i class="genericon-standard"></i></a>

显然,这不是我想要的。第二个代码(较短)哪里出错?

the_permalink()回显永久链接,get_permalink()返回永久链接。

所以第二种方式应该如下所示:

echo '<a href="' . get_permalink() . '" title="' . get_the_title() . '"><i class="genericon-standard"></i></a>';

我假设你使用的是Wordpress,所以你必须使用get_permalink()和get_the_title()而不是the_permalink,因为这个函数会回显结果并破坏你的字符串。

或者,您可以将永久链接存储在变量中,然后连接到字符串:

$permalink = get_permalink($post->ID); 

以下是文档:http://codex.wordpress.org/Function_Reference/the_permalink

在wordpress中get_permalink()和get_the_title()函数显示值