Page 1 of 1

What is $$?

Posted: Thu Jul 12, 2007 10:59 am
by smudge
Hi, I just read this post: viewtopic.php?t=70504 and came across this:

Code: Select all

while (list ($key,$val) = each ($_POST)) {
    $$key = $val;
}
What exactly is the $$? I understand what list and each do, but I have never seen $$ before. Is it a typo or does it have a special meaning?

Posted: Thu Jul 12, 2007 11:05 am
by Luke

Posted: Thu Jul 12, 2007 11:07 am
by smudge
Thanks much! You learn something new every day!

Posted: Thu Jul 12, 2007 11:56 am
by ReverendDexter
Something you don't ever want to use if you can avoid it ;)

Posted: Thu Jul 12, 2007 11:58 am
by Luke
yup, they're totally lame. If you're considering using variable variables, you likely need an array instead.

Let me qualify that: they're totally lame for most purposes -- they do come in handy in some very rare cases.

Posted: Thu Jul 12, 2007 1:01 pm
by RobertGonzalez
And if you have to use them, help out the maintainer of the code later by:
  1. Commenting what you are doing
  2. Commenting why you are doing it
  3. Using curly braces around the variable you are variablizing:

    Code: Select all

    <?php
    foreach($_POST as $k => $v) {
      ${$k} = $v;
    }
    ?>

Posted: Thu Jul 12, 2007 1:57 pm
by Benjamin
ReverendDexter wrote:Something you don't ever want to use if you can avoid it ;)
Although rare, there are times when they come in very, very handy.

Posted: Thu Jul 12, 2007 1:59 pm
by Benjamin
Everah wrote:Using curly braces around the variable you are variablizing
Keep in mind that the placement of braces can change the meaning. IE Whether your using an array index or character offset.

Posted: Thu Jul 12, 2007 2:06 pm
by Ollie Saunders
astions wrote:
Everah wrote:Using curly braces around the variable you are variablizing
Keep in mind that the placement of braces can change the meaning. IE Whether your using an array index or character offset.
Yep but I agree with Everah's advice to use them otherwise it looks like it could have been done by accident. Personally I find $obj->${$prop} infinitely more useful than ${$var}