变量中的变量

时间:2012-09-22 16:59:18

标签: php variables

出于某种原因,我似乎无法围绕这一点。

$welcome_message = "Hello there $name";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    $name = $this_name;
    echo $welcome_message."<br>";
}

如何每次更新$ welcome_message中的$ name变量?

使用变量但我似乎无法使其发挥作用。

由于

3 个答案:

答案 0 :(得分:6)

也许您正在寻找sprintf

$welcome_message = "Hello there %s";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    echo sprintf($welcome_message, $this_name), "<br>";
}

答案 1 :(得分:5)

这不起作用,因为$welcome_message仅在开始时评估一次(当$name可能仍未定义时)。您无法在$welcome_message内“保存”所需的表单,也可以随意“展开”它(除非您使用eval,这是完全可以避免的。)

移动在循环中设置$welcome_message的行:

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    $welcome_message = "Hello there $this_name";
    echo $welcome_message."<br>";
}

答案 2 :(得分:3)

你每次都可以像这样更新$ welcome_message ....

$welcome_message = "Hello there ".$name;

现在代码将是这样的......

$welcome_message = "Hello there ";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
echo $welcome_message.$this_name"<br>";
}