Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of complex (curly) syntax outside a string representation

Tags:

php

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.

like image 561
Radu Maris Avatar asked Jan 09 '13 15:01

Radu Maris


Video Answer


2 Answers

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.

like image 80
RickN Avatar answered Sep 20 '22 01:09

RickN


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.

like image 43
Czeslaw Avatar answered Sep 21 '22 01:09

Czeslaw