2011-11-22 67 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變量字符串爲更好的可讀性,使簡單的這種方式是最好的。