2009-06-20 31 views
17

私はsprintf()について多くのことを読んだ後ではありませんでしたが、私はそれを知るべきだと決めました。sprintf()が何も出力しないのはなぜですか?

私は先に進み、次のことをしました。

function currentDateTime() { 
    list($micro, $Unixtime) = explode(" ",microtime()); 
    $sec= $micro + date("s", $Unixtime); 
    $sec = mb_ereg_replace(sprintf('%d', $sec), "", ($micro + date("s", $Unixtime))); 
    return date("Y-m-d H:i:s", $Unixtime).$sec; 
} 

sprintf(currentDateTime()); 

これは何も印刷しません。一方、printf()関数を使用すると、次のようになります。

printf(currentDateTime()); 

結果は正常に出力されます。では、これらの2つの関数の違いは何ですか?sprintf()関数を正しく使用するにはどうすればよいですか?

答えて

57

sprintf()ストリング、printf()表示を返します。

次の二つが等しい:のprintf()は、文字列を出力しながら

printf(currentDateTime()); 
print sprintf(currentDateTime()); 
+24

が、私は '() '**サイレント**' printfの' に:) – deed02392

+0

@ deed02392考えて、それを覚えている:あなたは、次のような何かをする必要があると思います's'は文字列を表すのではないのですか? – Pacerier

14

sprintf()結果を文字列に出力します。すなわち標準出力にprintf()印刷を:

printf(currentDateTime()); 

と等価である:

echo sprintf(currentDateTime()); 
6

のsprintf()は、文字列を返します。

function currentDateTime() { 
    list($micro, $Unixtime) = explode(" ",microtime()); 
    $sec= $micro + date("s", $Unixtime); 
    $sec = mb_ereg_replace(sprintf('%d', $sec), "", ($micro + date("s", $Unixtime))); 
    return date("Y-m-d H:i:s", $Unixtime).$sec; 
} 

$output = sprintf(currentDateTime()); 
printf($output); 

http://www.php.net/sprintf

http://www.php.net/printf

関連する問題