我在代码中发现了这个,它是什么意思?和普通的$dir变量有什么区别?
global ${$dir};
$this->{$dir} = new $class();
我在代码中发现了这个,它是什么意思?和普通的$dir变量有什么区别?
global ${$dir};
$this->{$dir} = new $class();
它被称为复杂的花括号语法。
任何具有字符串表示的标量变量、数组元素或对象属性都可以通过这种语法包含。只需像在字符串外部一样编写表达式,然后将其用 { 和 } 包装起来即可。由于 { 不能被转义,所以只有在 $ 立即跟随 { 时才会识别此语法。使用 {\$ 可以获得一个字面上的 {$。
更多信息:
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex
它获取了$dir
变量的值并找到了与该名称相同的变量。
因此,如果$dir ='foo';
,那么${$dir}
就等同于$foo
。
同样地,如果$dir ='foo';
,那么$this->{$dir}
就等同于$this->foo
。
http://www.php.net/manual/en/language.variables.variable.php
$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
}
它们用于包装变量变量的名称。