简体   繁体   中英

What does {} mean?

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

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

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

它们用于包装变量变量的名称。

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM