Categories
Uncategorized

Variable Variables And Functions In PHP

$var_name = "foo";
$var_value = "bar";
$$var_name = $var_value;
echo $foo;
// ^ "bar"

What’s that $$about then?

PHP has some interesting dynamic capabilities around variable and function names. These can save you a few minutes in small scripts, but can cause maintenance headaches in large systems when you’re working with a team.

The gist of the $$ example above is that we’ve given a variable a name that was stored in another variable previously; the line $$var_name = $var_value; is evaluated to $foo = $var_value;. In most instances, the second option is what you should do.

The pattern can also be applied to function and method names:

class Foo {
    public function bar()
    {
        echo "bar called";
    }
}

$method_name = "bar";

$foo = new Foo;
$foo->$method_name();
// ^ "bar called"

In the example above, $foo->$method_name(); evaluates to $foo->bar();. Note that the () are not part of the method name, and can’t be evaluated from the variable:

$method_name = "bar()";
$foo->$method_name;
// ^ PHP Notice:  Undefined property: Foo::$bar() in php shell code on line 1

Trying to include the () will not work, as above.

It’s fun to play with these features, but they will quickly start to cause you problems in larger projects as you have to look more carefully to see how your changes will affect existing code. IDEs will also have more trouble evaluating your code as they can’t follow $obj->$method() as easily as an explicit $obj->doThing().

Remember to pay attention if you see a $ sign next to any other syntax: ::$ and {$ should also trigger alarm bells if you see them outside a string.

Your email will not be given to anyone else, ever.