Search code examples
phpvariable-variables

Is the dollar sign in a variable variable considered the dereference operator?


I was showing someone how you can create variable variable variables in PHP (I'd only recommend using them NEVER, it's horrible practice and you are a bad person if you use variable variable variables in actual production code), and they asked if the dollar sign acted as a dereference operator in this case.

It doesn't actually create a reference to the other variables, so I don't really see it as being the deref op. The documentation for variable variables doesn't even mention references at all.

Who's right? I don't think variable variables are creating references and therefore the dollar sign isn't the dereference operator.

Here's some sample code for your viewing pleasure (or pain given the contents):

<?php

$a = 'c';
$b = 'a';
$c = 'hello';

echo($$$b); //hello

Solution

  • Is the dollar sign in a variable variable considered the dereference operator?

    No. PHP does not possess a dereference operator.

    Variable variables shouldn't be thought of as dereferencing but, rather, accessing the symbol tree via a string. For example:

    $bar = 1;
    echo ${'bar'};
    

    You can perform this dynamically by using a variable instead of a string literal:

    $bar = 1;
    $foo = 'bar';
    echo ${$foo};
    

    PHP syntax allows you to remove the braces but it's still a matter of accessing the symbol table via a string. No referencing/dereferencing involved.