17

I found this in code, what does it mean and whats the difference between that and normal $dir variable?

global ${$dir};

$this->{$dir} = new $class();
zarcel
  • 1,211
  • 2
  • 16
  • 35

4 Answers4

40

Its called complex curly syntax.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognized when the $ immediately follows the {. Use {\$ to get a literal {$.

More info:

http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

kittycat
  • 14,983
  • 9
  • 55
  • 80
13

It is taking the value of the $dir variable and finding the variable with that name.

So if $dir = 'foo';, then ${$dir} is the same as $foo.

Likewise, if $dir = 'foo';, then $this->{$dir} is the same as $this->foo.

http://www.php.net/manual/en/language.variables.variable.php

Benjam
  • 5,285
  • 3
  • 26
  • 36
1

They are used to wrap the name of variable variables.

Mattt
  • 1,780
  • 14
  • 15
1

A dynamically created variable. For example:

$app = new App();
$app->someMethod('MyDB');

// global
$config = array('user' => 'mark', 'pass' => '*****');

class App {

    // MyDB instance
    protected $config;

    public function someMethod($class) {

        $dir = 'config';

        // $config = array('user' => 'mark', 'pass' => '*****')
        global ${$dir};
        // not static variable !!!
        $this->{$dir} = new $class();
    }
}

class MyDB {
  // body
}