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();
1

4 Answers 4

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

0
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

1

They are used to wrap the name of variable variables.

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
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.