【问题标题】: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 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2012-11-16
      • 2023-03-26
      • 1970-01-01
      • 2011-05-15
      • 2021-06-25
      • 1970-01-01
      相关资源
      最近更新 更多