dou8mwz5079 2013-10-07 15:49
浏览 29
已采纳

PHP使用这个'$$ var'是什么意思? [重复]

This question already has an answer here:

I am trying to learn php, and I saw this in a foreach loop what does it mean? I understand &$var which its a direct reference to the memory address of the object. But what does $$var means? what is it exactly?

This is the example.

    foreach($this->vars as $key => $value)
    {
        $$key = $value;
        echo "$$Key: " . $$key;
        echo "Key: " . $key;
        echo "<br/>";
        echo "Value: " . $value;
    }
</div>
  • 写回答

3条回答 默认 最新

  • dscss8996 2013-10-07 15:51
    关注

    You're looking at a variable variable. e.g.

    // original variable named 'foo'
    $foo = "bar";
    
    // reference $foo dynamically by evaluating $x
    $x = "foo";
    echo $$x; // "bar";
    echo ${$x}; // "bar" as well but the {} allows you to perform concatenation
    
    // different version of {} to show a more "complex" operation
    $y = "fo";
    $z = "o";
    echo ${$y . $z}; // "bar" also ("fo" . "o" = "foo")
    

    To show an example more closely matching your question:

    $foo = "foo";
    $bar = "bar";
    $baz = "baz";
    
    $ary = array('foo' => 'FOO','bar' => 'BAR','baz' => 'BAZ');
    foreach ($ary as $key => $value){
      $$key = $value;
    }
    
    // end result is:
    // $foo = "FOO";
    // $bar = "BAR";
    // $baz = "BAZ";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?