Page 132 - Beginning PHP 5.3
P. 132
Part II: Learning the Language
In case you ’ re wondering, file_get_contents() reads a file and returns its contents as a string.
You learn about it in more detail in Chapter 11 .
Now, say you were “ re - skinning ” your application for a different market, and wanted to use the
following template.txt file instead:
Your %s contains %d unread messages, and %d messages in total.
The format string contains the same conversion specifications, but the order is different. This would
result in the following message, which is clearly nonsense:
Your 36 contains 0 unread messages, and 4 messages in total.
Normally, the only way to fix this problem would be to change the order of the arguments in your PHP
code to match, which is overkill if you ’ re just re - skinning.
This is where argument swapping comes in. Using this technique, you can specify which argument you
want each conversion specification to refer to. Here ’ s how it works: after each percentage ( % ) symbol,
add the position of the argument you want to refer to (1 is the first argument after the format string, 2 is
the second, and so on) followed by a dollar ( $ ) symbol. So you could edit your template.txt file and
change your format string to the following:
Your %2$s contains %3$d unread messages, and %1$d messages in total.
Now your message displays correctly, even though you haven ’ t touched your PHP script:
Your Inbox contains 4 unread messages, and 36 messages in total.
Storing the Result Instead of Printing It
printf() is all very well, but what if you want to store the results in a variable for later use? You might
not be ready to display the string at the time you create it. This is where the sprintf() function comes
in handy. sprintf() behaves exactly like printf() , except it returns the resulting string rather than
printing it. For example:
<?php
$username = “Matt”;
$mailbox = “Inbox”;
$totalMessages = 36;
$unreadMessages = 4;
$messageCount = sprintf( file_get_contents( “template.txt” ), $totalMessages,
$mailbox, $unreadMessages );
?>
< p > Welcome, < ?php echo $username? > . < /p >
< p class=”messageCount” > < ?php echo $messageCount? > < /p >
Another variant of printf() is fprintf() , which writes the resulting string to an open file. To use
it, pass the file handle, followed by the format string, followed by the remaining arguments. Find out
more about files and file handles in Chapter 11 .
94
9/21/09 8:53:47 AM
c05.indd 94
c05.indd 94 9/21/09 8:53:47 AM