不同的 PHP 变量变量解析为同一个变量名是同一个变量吗?

Are different PHP variable variables that resolve to the same variable name the same variable?

假设我有一个用于创建可变变量的字符串数组:

$var_arr = ["item1", "item2", "item3"];
foreach ($var_arr as $item) {
    $$item = array();
}

然后在我的代码的其他地方,我必须根据不同的数据源重新创建变量变量:

$user_input = [ "prod1" => "widget", "qty1" => 3, "prod2" => "thingy", "qty2" => 1, "prod3" => "dingus", "qty3" => 7 ];
foreach ($user_input as $key => $value) {
    $a = "item" . substr($key, -1);
    array_push($$a, $value);
}

$$item 和 $$ 是同一个变量,还是引用不同的内存块?

两者是一样的,你在这里需要考虑的是你只是通过这里的每个赋值引用一个变量:

<?php
    $hello ="hello in variable";
    $array_hello = ["hello","Yellow"];
    $hello_var = "hello";
    $item = $array_hello[0];
    echo $$hello_var;
    echo $$item; //result same as above result
?>

这里需要注意的一件事是 ${$variable_name_string} 只是使用 $variable_name_string 来知道您想要的变量的名称,因此两者将访问相同的内存块,因为您在这里引用相同的变量。 这里要注意的另一件事是 PHP 7 从 PHP 5

的解释变化

表达式 $$foo['bar']['baz'] PHP 5 将其解释为 ${$foo['bar']['baz']} 而 PHP 7 将其解释为 ($$foo)['bar']['baz'] Refer PHP manual for more