5

I understand the usage of complex (curly) syntax within a string, but I don't understand it's purpose outside of a string.

I just found this code in CakePHP that I cannot understand:

// $class is a string containg a class name
${$class} =& new $class($settings);

If somebody could help me understand why is used here, and what is the difference between this and:

$class =& new $class($settings);

Thank you.

4

3 回答 3

4

Easiest way to understand this is by example:

class FooBar { }

// This is an ordinary string.
$nameOfClass = "FooBar";

// Make a variable called (in this case) "FooBar", which is the
// value of the variable $nameOfClass.
${$nameOfClass} = new $nameOfClass();

if(isset($FooBar))
    echo "A variable called FooBar exists and its class name is " . get_class($FooBar);
else
    echo "No variable called FooBar exists.";

Using ${$something} or $$something. is referred to in PHP as a "variable variable".

So in this case, a new variable called $FooBar is created and the variable $nameOfClass is still just a string.

于 2013-01-09T15:11:46.557 回答
2

An example where the usage of the complex (curly) syntax outside of a string would be necessary is when forming a variable name out of an expression, consisting of more than just one variable. Consider the following code:

$first_name="John";
$last_name="Doe";
$array=['first','last'];
foreach ($array as $element) {
    echo ${$element.'_name'}.' ';
}

In the code above the echo statement will output the value of the variable $first_name during the first loop, and the value of the variable $last_name during the second loop. If you were to remove the curly brackets the echo statement would try to output the value of the variable $first during the first loop and the value of the variable $last during the second loop. But since these variables were not defined the code would return an error.

于 2015-05-07T19:40:20.973 回答
0

The first example creates a dynamically named variable (name is the value of the class variable), the other overwrites the value of the class variable.

于 2013-01-09T15:11:35.763 回答