在php中,字符串串联(通过函数调用获得的字符串)是无序的.为什么?


In php, a string concatenation (with a string obtained by a function call) is disordered. Why?

这:

echo '<br>';
$author_single = sprintf( '/%s/single.php', 'francadaval' );
echo ( $author_single );
echo '<br>';
$author_single = sprintf( '/%s/single.php', the_author_meta( 'nickname') );
echo ( $author_single );
echo '<br>';
$nick = the_author_meta( 'nickname');
$author_single = sprintf( '/%s/single.php', $nick );
echo ( $author_single );

显示这个:

/francadaval/single.php
francadaval//single.php
francadaval//single.php

我看到串联顺序受到函数调用的影响,所以我尝试使用一个中间变量,但它不起作用。

使用点运算符代替sprintf或使用"/{$nick}/single.php"也可以。

函数the_author_meta是一个Wordpress函数,用于从文章作者那里获取数据,在这种情况下,它必须返回作者的昵称('franciadaval')。

如何使用作者昵称的函数调用使$author_single结果为'/francadaval/single.php'?

谢谢。

您应该使用get_the_author_meta而不是the_author_meta

  • the_author_meta显示作者元
  • get_the_author_meta返回作者元

似乎the_author_meta()函数不是返回值,而是输出值。

所以实际发生的是:

echo '<br>';
$author_single = sprintf( '/%s/single.php', 'francadaval' );
echo ( $author_single );

按预期输出/francadaval/single.php

echo '<br>';
$author_single = sprintf( '/%s/single.php', the_author_meta( 'nickname') );
echo ( $author_single );

内部函数the_author_meta首先运行,因此输出francadaval并返回null。然后以null作为第二个参数运行sprintf,返回//single.php。然后echo语句将//single.php附加到输出(现在已经具有francadaval),产生结果:francadaval//single.php

echo '<br>';
$nick = the_author_meta( 'nickname');
$author_single = sprintf( '/%s/single.php', $nick );
echo ( $author_single );

与上面的场景类似,您只是将函数调用拆分为单独的行。

正如soju所说,在这种情况下使用的正确函数是get_the_author_meta(),它会按预期返回值。

所以正确的代码是:

echo '<br>';
$author_single = sprintf( '/%s/single.php', get_the_author_meta( 'nickname') );
echo ( $author_single );