PHP:如何更新字符串中变量的值?(内联变量解析更新)


PHP: How to update values of variables in a string? (inline variable parsing updates)

有没有一种简单的方法可以使用{$var}语法更新字符串中已经存在的变量的值(不使用 eval 或替换函数)?

在此示例中:

$id_a=1; $id_b = 2;
echo $str = "The id {$id_a} is related to id {$id_b}'n";
// operations go in here that calculate new values for $id_ variables
$id_a=124214; $id_b=325325;
echo $str = "The id {$id_a} is related to id {$id_b}'n";

您注意到我将相同的字符串分配给$str两次。我的目标是只分配一次,每次echo $str是否更改$id_a$id_b时,$str都会更新值。

如果有一个功能可以实现这一点(即使它不是专门用于执行此操作),我还没有找到它,我很高兴知道它......

使用 sprintf 指定参数需要在字符串中出现的位置,并将 $id_a 和 $id_b 作为参数传递。

例如
$id_a=1; $id_b = 2;
$format = "The id %d is related to id %d'n";
echo sprintf($format, $id_a, $id_b);
// operations go in here that calculate new values for $id_ variables
$id_a=124214; $id_b=325325;
echo sprintf($format, $id_a, $id_b);

这样,您只需声明一次字符串的结构,并且可以在需要输出它的任何位置重用。这也具有能够将您的参数转换为各种格式的优点(查看 PHP 文档页面)

有了 Barmar 的想法,它使

function calculateString($id_a, $id_b) {
    return "The id {$id_a} is related to id {$id_b}'n";
}
$id_a=1; $id_b = 2;
echo $str = calculateString($id_a, $id_b);
$id_a=124214; $id_b=325325;
echo $str = calculateString($id_a, $id_b);