PHP printf存储和输出

tes*_*001 1 php printf output

我知道printf用于输出,而sprintf用于存储.

但是在这段代码中:

$str = printf('%.1f', 1.3);
echo $str;
Run Code Online (Sandbox Code Playgroud)

为什么输出1.33?我猜它会输出1.31.3?

rai*_*7ow 6

事实上,PHP中的 printf函数确实有两件事:打印其参数(根据格式字符串,作为第一个发送)并返回此打印字符串的长度.

通常printf不使用返回的值- 但在这种情况下不会.因为(格式化)printf这里必须打印'1.3'字符串(小数点后只有一位数),它的长度是3 - 所以它存储在$str变量中并在下一个语句中打印(带echo).所以整个产量是'1.33'.

作为旁注,这......

$str = print(1.3);
echo $str;
Run Code Online (Sandbox Code Playgroud)

...打印'1.31',因为print也会做两件事 - 打印其参数并返回1.