我试图了解更多关于PHP函数sprintf(),但php.net没有帮助我,因为我仍然困惑,为什么要使用它?
看看下面的例子。
为什么用这个:
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
当这样做是一样的,更容易写IMO:
$output = 'Here is the result: ' .$result. ' for this date ' .$date;
我是不是遗漏了什么?
我通常使用sprintf来确保来自用户输入的id是一个整数,例如:
// is better use prepared statements, but this is practical sometimes
$query = sprintf("SELECT * from articles where id = %d;",$_GET['article_id']);
Also是用来做基本的模板(html邮件或其他东西),所以你可以在很多地方重用模板:
$mail_body = "Hello %s, ...";
$oneMail = sprintf($mail_body, "Victor");
$anotherMail = sprintf($mail_body, "Juan");
用不同的表示形式(八进制、控制小数点等)格式化数字也非常有用。
Sprintf在格式化使用数字的字符串时特别有用。例如,
$oranges = -2.34;
echo sprintf("There are %d oranges in the basket", $oranges);
Output: There are -2 oranges in the basket
Oranges被格式化为整数(-2),但如果使用%u表示无符号值,则会换行为正数。为了避免这种行为,我使用绝对函数abs(),将数字四舍五入,如下所示:
$oranges = -5.67;
echo sprintf("There are %d oranges in the basket", abs($oranges));
Output: There are 5 oranges in the basket
最终的结果是一个具有高可读性、逻辑结构、清晰格式和根据需要灵活添加额外变量的语句。随着变量数量的增加以及操作这些变量的函数的组合,好处变得更加明显。最后一个例子:
$oranges = -3.14;
$apples = 1.5;
echo sprintf("There are %d oranges and %d apples", abs($oranges), abs($apples));
Output: There are 3 oranges and 4 apples
sprintf语句的左边清楚地表达了字符串和期望值的类型,而右边清楚地表达了使用的变量以及如何操作它们。