2012-11-30 221 views
17

我在代码中发现了这个,它和普通的$ dir变量有什么区别?{}是什么意思?

global ${$dir}; 

$this->{$dir} = new $class(); 
+2

这是动态的名称。更多http://stackoverflow.com/questions/9257505/dynamic-variable-names-php –

回答

40

它被称为复杂的卷曲语法。

任何具有字符串 表示的标量变量,数组元素或对象属性都可以通过此语法包含在内。只需使用与字符串外部相同的方式编写 表达式,然后 将其包装在{和}中。由于{不能被转义,这个语法将只在$紧跟在{之后才会被识别出来, 。使用{\ $到 获得一个文字{$。

更多信息:

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

1

它们被用来包裹变量变量的名称。

1

动态创建的变量。例如:

$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 
}