我试图了解更多关于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时必须小心:
$a = 'Anton';
$b = 'Bert';
$c = 'Corni';
$d = 'Dora';
$e = 'Emiel';
$f = 'Falk';
$loops = 10000000;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = $a . $b . $c . $d . $e . $f;
}
$concatTime = microtime(true) - $time;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = "$a $b $c $d $e $f";
}
$concat2Time = microtime(true) - $time;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = sprintf('%s %s %s %s %s %s', $a, $b, $c, $d, $e, $f);
}
$sprintfTime = microtime(true) - $time;
echo 'Loops: ' . $loops . '<br>';
echo '\'$a . $b . $c . $d . $e . $f\'' . ' needs ' . $concatTime . 's<br>';
echo '"$a $b $c $d $e $f"' . ' needs ' . $concat2Time . 's<br>';
echo 'sprintf(\'%s %s %s %s %s %s\', $a, $b, $c, $d, $e, $f)' . ' needs ' . $sprintfTime . 's<br>';
这会导致以下时间(在我的本地机器上使用PHP 7.2):
循环:10000000
“一美元。b美元。$ c。美元d。$ e。$f'需要1.4507689476013s
“$a $b $c $d $e $f”需要1.9958319664001s
sprintf (' % s % s % s % s % s % s’,一个美元,美元b, c,美元美元d, e,美元$ f)需要9.1771278381348秒
sprintf有许多用例,但我使用它们的一种方式是在数据库中存储这样的字符串:'Hello, My Name is %s',或将其作为PHP类中的常量。这样当我想要使用该字符串时,我可以简单地这样做:
$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'
本质上,它允许在代码中进行一些分离。如果我在代码中的许多地方使用“Hello, My Name is %s”,我可以在一个地方将其更改为“%s是我的名字”,并且它会自动更新其他任何地方,而不必去到每个实例并在连接中移动。