Reputation: 1241
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();
Upvotes: 17
Views: 1943
Reputation: 93
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
}
Upvotes: 1
Reputation: 5316
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
Upvotes: 13
Reputation: 15045
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
Upvotes: 40