【问题标题】:sprintf argument swapping and HEREDOCsprintf 参数交换和 HEREDOC
【发布时间】:2013-11-10 23:47:58
【问题描述】:
我正在尝试以这种方式在 heredoc 上使用 sprintf。它不会工作。知道如何解决这个问题吗?
$i = <<<EOD
This is your invoice for %1$s %1$s %1$s %1$s
EOD;
$year = '2013';
$i = sprintf($i,$year);
echo $i;
注意:未定义变量:s in
【问题讨论】:
标签:
php
printf
heredoc
nowdoc
【解决方案1】:
因为 HEREDOC 的行为类似于双引号字符串,PHP 试图将 $s 插入为变量。改用NOWDOC
$i = <<<'EOD'
This is your invoice for %1$s %1$s %1$s %1$s
EOD;
【解决方案2】:
或者只是避开美元符号:
$i = <<<EOD
This is your invoice for %1\$s %1\$s %1\$s %1\$s
EOD;
这很有用,例如在没有 nowdoc 语法的 PHP 5.2 中。