Whilst I don’t advocate assigning variable variables, there are times when you need to create variables in PHP dynamically.

What is a Variable Variable?

A variable variable is a variable that can be set dynamically. For instance the normal way to create a variable in PHP would be:


$foo = 'bar';

But what happens when you’re setting a variable dynamically, i.e. it doesn’t exist already and it’s dependant on user input or an unpredictable event? The solution… a Variable Variable


$foo = 'bar';

$$foo = 'hello';

echo $bar; // this will output 'hello'

This may seem useless to you but after just over 5 years of programming I’d finally found a sane some what safe use for it. I had an object that has a property that contained an array of data, I wanted to be able to access that data from within an included file in my function. To do this I had to assign a load of variables that were dynamically set within the object… you know what, let me just show you!

class Template {

    protected $variables = array();

    public function set($key, $value){
        if($key === 'this'){
            throw new Exception('Key cannot be set to "this"');
        }

        $this->variables[$key] = $value;
    }

    /**
     * Outputs the fully rendered view
     *
     * @param bool $output
     */
    public function output($output = true){
        $this->_loadTemplate();
        $this->output = ob_get_clean();
        if($output === true){
            echo $this->output;
        }
    }

    private function _loadTemplate(){

        foreach($this->variables as $key => $value){
            $$key = $value;
        }

        require_once 'layout/' . $this->layout . '.phtml';
    }

}

So now in my layout, instead of having to do this to get my template variables..


<?php echo $this->variables['foo'] ?>

I can use this


<?php echo $foo; ?>

All done, also as a side note, people who use

<?=$fool; ?>

to output content, stop it! You’re shooting your self in the foot, when you migrate to a server that doesn’t support short tags and you can’t change it, you’ll be fucked and annoyed!

Use

<?php echo $foo; ?>

Instead, the extra key strokes saves the weeks of headache!