2011-11-22 61 views
0

如何使用printf来处理参数,而不管它们的类型如何? (类似PDO中预备声明中的绑定参数)。使用带参数的printf

例如为:

printf("Hello $s, you have $s new notifications.", $username, $newNotifications); 

我想类似的东西,并没有工作。

+3

是不是'%s'为一个字符串? –

回答

0

printf需要知道如何格式化参数。你可以只echo他们,而不是使用.连接符:

echo "Hello " . $username . ", you have " . $newNotifications . " new notifications."; 
1

看那man page

基本上,当你应该使用%s时,你使用的是$s。但是,你可以只使用printecho以字符串:

print "Hello ".$username.", you have ".$newNotifications." new notifications."; 
+0

你说得对,我使用的是$ s而不是%s。它现在有效,谢谢。 此外,我发现它更干净,使用参数,而不是串联,如果我正在处理一个大字符串。这就是为什么我想使用参数 – federicot

+0

@JohnDoe完全相反,在长的字符串中,你将不得不在你的手指上占位符 –

0
echo "Hello $username, you have $newNotifications new notifications."; 

注意良好语法高亮将emphase变量字符串为更好的可读性,使简单的这种方式是最好的。