PHP help with using variable inside code
I have this line of code: <?php global $bp; query_posts( 'author=$bp-&g开发者_开发百科t;displayed_user->id' ); if (have_posts()) : ?>
but it doesn't work as expected. Probably because it's not grabbing the $bp->displayed_user->id
part correctly. How do I do it?
Thanks
<?php global $bp; query_posts( 'author=' . $bp->displayed_user->id ); if (have_posts()) : ?>
In single quoted strings variables will not be expanded. See documentation here: http://php.net/manual/en/language.types.string.php
It isn't working because it's treating the 'author=$bp->displayed_user->id'
as a string rather than inlining the contents of the variable. (This is the main difference between using single and double quotes. Have a read of the PHP strings manual page for more information.)
To fix this, try either:
query_posts('author=' . $bp->displayed_user->id);
or
query_posts("author={$bp->displayed_user->id}");
That said, I'd personally recommend the first approach, as it's more explicit what's going on.
Using single quotes makes PHP do not fetch the variable value. Instead of using single quotes you can use double quotes:
<?php
global $bp;
query_posts( "author={$bp->displayed_user->id}" ); if (have_posts()) :
?>
Or this way (I thik that is better):
<?php
global $bp;
query_posts( 'author=' . $bp->displayed_user->id ); if (have_posts()) :
?>
精彩评论